package game

import (
	// "fmt"

	"fmt"
	"math/rand"
	"sort"

	"github.com/robfig/cron/v3"

	// "math"
	"server/GoUtil"
	"server/MergeConst"
	"server/db"
	"server/gamedata"
	"server/msg"
	"strconv"
	"strings"
	"time"

	"server/pkg/github.com/name5566/leaf/timer"

	cmap "github.com/orcaman/concurrent-map/v2"
	"google.golang.org/protobuf/proto"
)

type PlayerDataModule interface {
	LoadDataFromDB(key interface{}) bool
	SaveDataFromDB(key interface{}) bool
	SetPlayer(p *Player)
	GetPlayer() *Player
	GetData() interface{}
	ClearData() bool
	Reconnect(bool)
	AutoSaveInterval()
}

type PlayerData struct {
	Name         string
	IsHaveDataDb bool
	M_Player     *Player
}

func (d *PlayerData) SetPlayer(p *Player) {
	d.M_Player = p
}

func (d *PlayerData) GetPlayer() *Player {
	return d.M_Player
}

func (d *PlayerData) Reconnect(b bool) {

}
func (d *PlayerData) AutoSaveInterval() {

}

func (d *PlayerData) LoadDataFromDB(UserName interface{}) bool {

	return true
}

func (d *PlayerData) SaveDataFromDB(Key interface{}) bool {

	return true
}
func (d *PlayerData) ClearData() bool {

	return true
}
func (d *PlayerData) GetData() interface{} {
	res := struct{}{}
	return res
}

func NewPlayerData(name string, player *Player) *PlayerData {
	return &PlayerData{
		Name:     name,
		M_Player: player,
	}
}

type PlayerBaseData struct {
	*PlayerData
	Data           msg.ResPlayerBaseInfo
	KeyValueData   msg.ResKeyValueData
	MLeafTimer     *timer.Timer
	MTicker        *time.Ticker
	McronSave      *cron.Cron
	McronSaveID    cron.EntryID
	Mdispatr       *timer.Dispatcher
	DailyRenewTime int32
	isKeyValueDb   bool
}

func (p *PlayerBaseData) GetData() interface{} {
	return &p.Data
}

func (p *PlayerBaseData) LoadDataFromDB(UserName interface{}) bool {
	sqlStr := "SELECT * FROM t_player_baseinfo WHERE user_name = ?"
	sqlStruck := db.ResPlayerBaseInfo{}
	if err := db.SqlDb.Get(&sqlStruck, sqlStr, UserName); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		return false
	}
	sqlStr1 := "SELECT * FROM t_player_auto_pup WHERE dwUin = ?"
	sqlStruck1 := db.SqlKeyValueStruct{}
	p.isKeyValueDb = true
	if err := db.SqlDb.Get(&sqlStruck1, sqlStr1, sqlStruck.DwUin); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.isKeyValueDb = false
	} else {
		p.isKeyValueDb = true
	}
	p.KeyValueData.KeyValues = make(map[string]string)

	p.Data.Diamond = sqlStruck.Diamond
	p.Data.DwUin = sqlStruck.DwUin
	p.Data.Energy = sqlStruck.Energy
	p.Data.Star = sqlStruck.Star
	p.Data.RecoverTime = sqlStruck.RecoverTime
	p.Data.Level = sqlStruck.Level
	p.Data.Exp = sqlStruck.Exp
	p.Data.StartOrderId = sqlStruck.StartOrderId
	p.Data.MusicCode = sqlStruck.MusicCode
	p.Data.Guild = sqlStruck.Guild
	p.Data.PackUnlockCount = sqlStruck.PackUnlockCount
	p.Data.LastPlayTime = sqlStruck.LastPlayTime
	p.Data.EnergyBuyCount = sqlStruck.EnergyBuyCount
	p.Data.LoginTime = int32(time.Now().Unix())
	p.Data.UserName = sqlStruck.UserName
	p.Data.LogoutTime = sqlStruck.LogoutTime
	p.Data.Todayolinetime = sqlStruck.Todayolinetime
	p.Data.Rolecreatetime = sqlStruck.Rolecreatetime
	p.Data.LastChampGroupID = sqlStruck.LastChampGroupID
	p.Data.ChampshipsGroupID = sqlStruck.ChampshipsGroupID
	p.DailyRenewTime = sqlStruck.DailyRenewTime
	p.Data.NoAd = sqlStruck.NoAd
	p.Data.FaceBookId = sqlStruck.FaceBookId
	p.McronSave = cron.New()
	p.Reconnect(false)

	if sqlStruck1.Keys != "" {
		arr := strings.Split(sqlStruck1.Keys, ";")
		arr1 := strings.Split(sqlStruck1.Vals, ";")
		for i := 0; i < len(arr); i++ {
			p.KeyValueData.KeyValues[arr[i]] = arr1[i]
		}
	}
	p.AddCompensateEmail()
	return true
}

func (p *PlayerBaseData) ProcessCallback() {
	deltaTime := p.Data.LoginTime - p.Data.LogoutTime

	if p.M_Player.GetGameData("Player7DayCallBackData") == nil {
		data := &Player7DayCallBackData{PlayerData: NewPlayerData("Player7DayCallBackData", p.M_Player)}
		ok := data.LoadDataFromDB(p.Data.DwUin)
		if ok {
			p.M_Player.playerdata["Player7DayCallBackData"] = data
			p.M_Player.playerdataIF["Player7DayCallBackData"] = data
		}
	}

	if deltaTime >= 7*3600*24 && p.Data.LogoutTime > 0 {
		p.M_Player.playerdataIF["Player7DayCallBackData"].(*Player7DayCallBackData).OpenNewCallBack()
	} else {
		p.M_Player.playerdataIF["Player7DayCallBackData"].(*Player7DayCallBackData).ProcessIsOutline()
	}
}

func (p *PlayerBaseData) IsPlayerLoginCallback() bool {
	return p.Data.LoginTime-p.Data.LogoutTime >= 7*3600*24 && p.Data.LogoutTime > 0
}

func (p *PlayerBaseData) GetRoleCreateTime() int32 {
	return p.Data.Rolecreatetime
}

func (p *PlayerBaseData) Reconnect(b bool) {
	curtime := time.Now().Unix()
	delta := curtime - (int64)(p.Data.RecoverTime)
	Addsta := delta / MergeConst.G_Sta_RecoverTime

	if p.Data.Level >= 2 {
		p.General7DayData()
	}
	if p.GetMaxEnergy() > p.Data.Energy {
		p.Data.Energy = p.Data.Energy + int32(Addsta)
		if p.Data.Energy > p.GetMaxEnergy() {
			p.Data.Energy = p.GetMaxEnergy()
		}

	} else {

	}
	p.Data.RecoverTime = p.Data.RecoverTime + int32(Addsta*MergeConst.G_Sta_RecoverTime)
	go func() {
		// 注释内容也可以使用
		t1 := (curtime) - (int64)(p.Data.RecoverTime)
		p.Mdispatr = timer.NewDispatcher(1)
		p.MLeafTimer = p.Mdispatr.AfterFunc(time.Duration(t1)*time.Second, func() {
			timeStamp := (int64)(time.Now().Unix())
			p.NotifyAddSta(1, timeStamp)
			p.MLeafTimer = nil
			p.MTicker = time.NewTicker(time.Second * time.Duration(MergeConst.G_Sta_RecoverTime))

			for {
				select {
				case <-p.MTicker.C:
					timeStamp := (int64)(time.Now().Unix())
					p.NotifyAddSta(1, timeStamp)
				}
			}
		})

		(<-p.Mdispatr.ChanTimer).Cb()

	}()

	if G_GameLogicPtr.DailyTaskTimestamp > (int64)(p.DailyRenewTime) {
		p.DailyRenewTime = int32(G_GameLogicPtr.DailyTaskTimestamp)
		p.Data.EnergyBuyCount = 0
	}
	GoUtil.RegisterEvent(MergeConst.Notify_Daily_Renew, p.Notify_Daily_Renew, p)

	p.McronSaveID, _ = p.McronSave.AddFunc("@every 60s", func() {
		// G_getGameLogic().Mlogger.Debug("tick every 60 second")
		// fmt.Println("tick every 60 second")
		p.M_Player.AutoSaveData()
	})

	p.McronSave.Start()
}

func (p *PlayerBaseData) AddCompensateEmail() {
	G_GameLogicPtr.MOldPlayerCompensateMgr.SendEmailToDb(p.Data.UserName, p.Data.DwUin)
}

func (p *PlayerBaseData) SetChampshipID(ChampshipsGroupID int32, isNotify bool) {
	p.Data.LastChampGroupID = p.Data.ChampshipsGroupID
	p.Data.ChampshipsGroupID = ChampshipsGroupID

	if isNotify {
		notify := &msg.NotifyChampshipOpen{}
		notify.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
		notify.LastChampshipsGroupID = p.Data.LastChampGroupID
		notify.ChampshipsGroupID = p.Data.ChampshipsGroupID
		agent := p.GetPlayer().GetAgentByPlayer()
		data, _ := proto.Marshal(notify)
		G_getGameLogic().PackResInfo(agent, "NotifyChampshipOpen", data)

	}

	p.SaveDataFromDB("")
}

func (p *PlayerBaseData) Notify_Daily_Renew(param []interface{}) {
	p.Data.EnergyBuyCount = 0
	p.DailyRenewTime = int32(G_GameLogicPtr.DailyTaskTimestamp)
	notify := &msg.NotifyRenewBuyEnergyCnt{}
	notify.DwUin = p.M_Player.M_DwUin
	notify.CurCnt = 0

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyRenewBuyEnergyCnt", data)
	p.SaveDataFromDB("")
}

func (p *PlayerBaseData) SaveDataFromDB(Key interface{}) bool {
	// G_getGameLogic().Mlogger.Debug("SaveDataFromDB:", p.Data.DwUin)
	sqlStruck := db.ResPlayerBaseInfo{}
	sqlStruck.Diamond = p.Data.Diamond
	sqlStruck.DwUin = p.Data.DwUin
	sqlStruck.Energy = p.Data.Energy
	sqlStruck.Star = p.Data.Star
	sqlStruck.RecoverTime = p.Data.RecoverTime
	sqlStruck.Level = p.Data.Level
	sqlStruck.Exp = p.Data.Exp
	sqlStruck.StartOrderId = p.Data.StartOrderId
	sqlStruck.MusicCode = p.Data.MusicCode
	sqlStruck.Guild = p.Data.Guild
	sqlStruck.PackUnlockCount = p.Data.PackUnlockCount
	sqlStruck.LastPlayTime = p.Data.LastPlayTime
	sqlStruck.EnergyBuyCount = p.Data.EnergyBuyCount
	sqlStruck.LoginTime = p.Data.LoginTime
	sqlStruck.UserName = p.Data.UserName
	sqlStruck.LogoutTime = p.Data.LogoutTime
	sqlStruck.Todayolinetime = p.Data.Todayolinetime
	sqlStruck.Rolecreatetime = p.Data.Rolecreatetime
	sqlStruck.DailyRenewTime = p.DailyRenewTime
	sqlStruck.NoAd = p.Data.NoAd
	sqlStruck.ChampshipsGroupID = p.Data.ChampshipsGroupID
	sqlStruck.LastChampGroupID = p.Data.LastChampGroupID
	sqlStruck.FaceBookId = p.Data.FaceBookId
	db.FormatAllMemUpdateDb(&sqlStruck, "t_player_baseinfo", "dwUin")
	p.IsHaveDataDb = true
	return true
}

func (p *PlayerBaseData) GetMaxEnergy() int32 {
	MaxSta := MergeConst.G_Sta_Limit

	if p.Data.Level < 7 {
		MaxSta = MergeConst.G_Sta_Limit
	} else if p.Data.Level < 12 {
		MaxSta = 120
	} else if p.Data.Level < 19 {
		MaxSta = 130
	} else if p.Data.Level < 27 {
		MaxSta = 135
	} else if p.Data.Level < 38 {
		MaxSta = 140
	} else if p.Data.Level < 44 {
		MaxSta = 145
	} else if p.Data.Level < 59 {
		MaxSta = 150
	} else {
		MaxSta = 155
	}
	return MaxSta
}

func (p *PlayerBaseData) NotifyAddSta(cnt int, timeStamp int64) {
	if p.GetMaxEnergy() <= p.Data.Energy {
		return
	}
	G_getGameLogic().Mlogger.Debug("NotifyAddSta:", p.Data.DwUin)
	p.Data.Energy = p.Data.Energy + int32(cnt)
	p.Data.RecoverTime = int32(timeStamp)

	notify := &msg.NotifyAddEnergy{}
	notify.AddCnt = int32(cnt)
	notify.DwUin = p.M_Player.M_DwUin

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyAddEnergy", data)
}

func (p *PlayerBaseData) UpdateBaseItemInfo(update *msg.UpdateBaseItemInfo) {
	for k, v := range update.MUpdateItem {
		switch k {
		case 1:
			p.Data.Energy = v
		case 2:
			p.Data.Star = v
		case 3:
			p.Data.Diamond = v
		case 4:
			p.Data.EnergyBuyCount = v
		case 5:
			p.Data.Level = v
			if v >= 2 {
				p.General7DayData()
			}
		case 6:
			p.Data.Exp = v
		case 7:
			p.Data.StartOrderId = fmt.Sprintf("%d", v)
		case 8:
			p.Data.Guild = v
		case 9:
			p.Data.PackUnlockCount = v
		case 10:
			p.Data.EmitOrderCnt = v
		case 11:
			p.Data.LastPlayTime = v
		}
	}
	p.SaveDataFromDB("")
}

func (p *PlayerBaseData) General7DayData() {
	if p.M_Player.GetGameData("Player7DayData") == nil {
		data := &Player7DayData{PlayerData: NewPlayerData("Player7DayData", p.M_Player)}
		ok := data.LoadDataFromDB(p.Data.DwUin)
		if ok {
			p.M_Player.playerdata["Player7DayData"] = data
			p.M_Player.playerdataIF["Player7DayData"] = data
		}
	}
	p.M_Player.playerdataIF["Player7DayData"].(*Player7DayData).Notify7DayLoginData(int32(time.Now().Unix()))

}

func (p *PlayerBaseData) ReqRemoveAd(buf []byte) {
	req := &msg.ReqRemoveAd{}
	res := &msg.ResRemoveAd{}
	proto.Unmarshal(buf, req)

	p.Data.NoAd = 1
	res.ResultCode = 0
	p.SaveDataFromDB("")

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResRemoveAd", data)
}

func (p *PlayerBaseData) ResPlayerBaseInfo(player *Player) {
	if player != p.M_Player {
		return
	}
	if p.Data.Level >= 2 {
		p.General7DayData()
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResPlayerBaseInfo", data)

	data1, _ := proto.Marshal(&p.KeyValueData)
	G_getGameLogic().PackResInfo(agent, "ResKeyValueData", data1)
}

func (p *PlayerBaseData) ReqBindFacebookAccount(buf []byte) {
	req := &msg.ReqBindFacebookAccount{}
	res := &msg.ResBindFacebookAccount{}
	proto.Unmarshal(buf, req)

	sqlStr := "SELECT * FROM t_player_baseinfo WHERE FaceBookId = ?"
	sqlStruck := db.ResPlayerBaseInfo{}
	isHaveOther := false

	if err := db.SqlDb.Get(&sqlStruck, sqlStr, req.BindAccountId); err != nil {
		isHaveOther = false
	} else {
		isHaveOther = true
	}
	if isHaveOther {
		if sqlStruck.DwUin == p.Data.DwUin {
			res.ResultCode = MergeConst.Protocol_FaceBook_Binded
		} else {
			res.ResultCode = MergeConst.Protocol_FaceBook_Binded_other
		}
	} else {
		res.ResultCode = 0
		p.Data.FaceBookId = req.BindAccountId
		res.BindAccountId = req.BindAccountId
		p.SaveDataFromDB("")
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResBindFacebookAccount", data)
}

func (p *PlayerBaseData) ReqUnBindFacebook(buf []byte) {
	req := &msg.ReqUnBindFacebook{}
	res := &msg.ResUnBindFacebook{}
	proto.Unmarshal(buf, req)

	res.ResultCode = 0
	res.BindAccountId = req.BindAccountId
	p.Data.FaceBookId = ""
	p.SaveDataFromDB("")

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResUnBindFacebook", data)
}
func (p *PlayerBaseData) ReqOnlyBindFacebook(buf []byte) {
	req := &msg.ReqOnlyBindFacebook{}
	res := &msg.ResOnlyBindFacebook{}
	proto.Unmarshal(buf, req)

	sqlStr := "SELECT * FROM t_player_baseinfo WHERE FaceBookId = ?"
	sqlStruck := db.ResPlayerBaseInfo{}
	isHaveOther := false

	if err := db.SqlDb.Get(&sqlStruck, sqlStr, req.BindAccountId); err != nil {
		isHaveOther = false
	} else {
		isHaveOther = true
	}
	if isHaveOther {
		if sqlStruck.DwUin == p.Data.DwUin {
			res.ResultCode = MergeConst.Protocol_FaceBook_Binded
		} else {
			sqlStruck.FaceBookId = ""
			db.FormatAllMemUpdateDb(&sqlStruck, "t_player_baseinfo", "dwUin")
			res.ResultCode = 0
			p.Data.FaceBookId = req.BindAccountId
			res.BindAccountId = req.BindAccountId
			p.SaveDataFromDB("")
		}
	} else {
		res.ResultCode = 0
		p.Data.FaceBookId = req.BindAccountId
		res.BindAccountId = req.BindAccountId
		p.SaveDataFromDB("")
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResOnlyBindFacebook", data)
}

func (p *PlayerBaseData) ReqSynGameData(buf []byte) {
	req := &msg.ReqSynGameData{}
	res := &msg.ResSynGameData{}
	proto.Unmarshal(buf, req)

	sqlStr := "SELECT * FROM t_player_baseinfo WHERE FaceBookId = ?"
	sqlStruck := db.ResPlayerBaseInfo{}
	isHaveOther := false

	if err := db.SqlDb.Get(&sqlStruck, sqlStr, req.NewFBId); err != nil {
		isHaveOther = false
	} else {
		isHaveOther = true
	}
	if sqlStruck.DwUin == p.M_Player.M_DwUin {
		return
	}

	if OldPlayer, ok := G_GameLogicPtr.M_Players[sqlStruck.DwUin]; ok {
		agent := OldPlayer.GetAgentByPlayer()
		// notify := &msg.ForceKickOut{}
		notify := &msg.ResSynGameData{}
		data, _ := proto.Marshal(notify)
		if agent != nil {
			G_getGameLogic().PackResInfo(agent, "ResSynGameData", data)
		}
		OldPlayer.ClearData()
		delete(G_GameLogicPtr.M_Players, sqlStruck.DwUin)
	} else {
		player := G_GameLogicPtr.FindOfflinePlayer(sqlStruck.DwUin)
		if player != nil {
			timer1, _ := G_GameLogicPtr.MReadyToRemoveList[player]
			timer1.Disabled()
			G_GameLogicPtr.Mdispatr.ChanTimer <- timer1
			timer1.Stop()
			delete(G_GameLogicPtr.MReadyToRemoveList, player)
		} else {

		}
	}

	if isHaveOther {
		if sqlStruck.DwUin == p.Data.DwUin {
			res.ResultCode = MergeConst.Protocol_FaceBook_Binded
		} else {
			ReplaceName := sqlStruck.UserName
			UserName := p.Data.UserName
			res.ResultCode = 0

			sqlStr1 := "SELECT * FROM t_account WHERE user_name = ?"
			sqlAccStruck1 := db.Db_Account{}
			if err2 := db.SqlDb.Get(&sqlAccStruck1, sqlStr1, UserName); err2 != nil {

			} else {
				sqlAccStruck1.UserName = ""
				db.FormatAllMemUpdateDb(&sqlAccStruck1, "t_account", "auto_id")
			}
			p.Data.UserName = ""
			p.SaveDataFromDB("")

			sqlStruck.FaceBookId = req.NewFBId
			sqlStruck.UserName = UserName
			db.FormatAllMemUpdateDb(&sqlStruck, "t_player_baseinfo", "dwUin")

			sqlStr := "SELECT * FROM t_account WHERE user_name = ?"
			sqlAccStruck := db.Db_Account{}

			if err2 := db.SqlDb.Get(&sqlAccStruck, sqlStr, ReplaceName); err2 != nil {

			} else {
				sqlAccStruck.UserName = UserName
				db.FormatAllMemUpdateDb(&sqlAccStruck, "t_account", "auto_id")
			}

		}
	} else {
		res.ResultCode = 0

	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResSynGameData", data)
}

func (p *PlayerBaseData) UpdateKeyValueData(update *msg.UpdateKeyValueData) {

	for k := range p.KeyValueData.KeyValues {
		delete(p.KeyValueData.KeyValues, k)
	}
	var strarr = []string{}
	var strarr1 = []string{}
	for k, v := range update.KeyValues {
		p.KeyValueData.KeyValues[k] = v
		strarr = append(strarr, k)
		strarr1 = append(strarr1, v)
	}

	sqlStruck := db.SqlKeyValueStruct{}
	sqlStruck.Keys = strings.Join(strarr, ";")
	sqlStruck.Vals = strings.Join(strarr1, ";")
	sqlStruck.DwUin = p.Data.DwUin

	if p.isKeyValueDb {
		db.FormatAllMemUpdateDb(&sqlStruck, "t_player_auto_pup", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&sqlStruck, "t_player_auto_pup")
	}

	p.isKeyValueDb = true
}

func (p *PlayerBaseData) ClearData() bool {
	p.Data.LogoutTime = int32(time.Now().Unix())
	p.SaveDataFromDB("")
	G_getGameLogic().Mlogger.Debug("ClearData:", p.Data.DwUin)
	GoUtil.RemoveEvent(MergeConst.Notify_Daily_Renew, p.Notify_Daily_Renew, p)
	p.McronSave.Remove(p.McronSaveID)
	p.McronSave.Stop()

	if p.MLeafTimer != nil {
		p.MLeafTimer.Stop()
		p.MLeafTimer = nil
	}
	if p.MTicker != nil {
		p.MTicker.Stop()
		p.MTicker = nil
	}
	return true
}

/////////////////////////////////////

type PlayerEmitUnlockData struct {
	*PlayerData
	Data msg.ResPlayerEmitUnlockData
}

func (p *PlayerEmitUnlockData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_emit_unlock WHERE dwUin = ?"
	sqlStruck := db.SqlEmitUnlockStruct{RenewTime: 0}
	p.Data.MEmitUnlockData = make(map[int32]int32)

	if err := db.SqlDb.Get(&sqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}
	if sqlStruck.Value != "" {
		arr := strings.Split(sqlStruck.Value, "_")
		for i := 0; i < len(arr); i++ {
			ss := strings.Split(arr[i], ",")
			id, err := strconv.ParseInt(ss[0], 10, 32)
			cnt, _ := strconv.ParseInt(ss[1], 10, 32)
			if err != nil {
				panic(err)
			}
			p.Data.MEmitUnlockData[int32(id)] = int32(cnt)
		}
	}
	p.Data.DwUin = dwUin.(int32)
	p.Data.RenewTime = sqlStruck.RenewTime

	p.Reconnect(false)
	return true
}

func (p *PlayerEmitUnlockData) Reconnect(b bool) {
	if G_GameLogicPtr.DailyTaskTimestamp > (int64)(p.Data.RenewTime) {
		p.Data.RenewTime = int32(G_GameLogicPtr.DailyTaskTimestamp)
		for k := range p.Data.MEmitUnlockData {
			p.Data.MEmitUnlockData[k] = 0
		}
		if b {
			agent := p.GetPlayer().GetAgentByPlayer()
			data, _ := proto.Marshal(&p.Data)
			G_getGameLogic().PackResInfo(agent, "NotifyDailyRenewEmitUnlock", data)
		}
	}
	GoUtil.RegisterEvent(MergeConst.Notify_Daily_Renew, p.NotifyDailyRenewEmitUnlock, p)
}

func (p *PlayerEmitUnlockData) GetUnlockCntByID(id int32) int32 {
	cnt, ok := p.Data.MEmitUnlockData[id]
	if ok {
		return cnt
	}
	return 0
}

func (p *PlayerEmitUnlockData) ClearData() bool {
	p.SaveDataFromDB("")
	GoUtil.RemoveEvent(MergeConst.Notify_Daily_Renew, p.NotifyDailyRenewEmitUnlock, p)
	return true
}

func (p *PlayerEmitUnlockData) SaveDataFromDB(Key interface{}) bool {
	var strarr []string
	for k, v := range p.Data.MEmitUnlockData {
		str := fmt.Sprintf("%d,%d", k, v)
		strarr = append(strarr, str)
	}
	str_concat := strings.Join(strarr, "_")
	// sqlStr := "UPDATE user SET age = ?, degree = ? WHERE id = ?"
	// result, err := SqlDb.Exec(sqlStr, 22, 10, 4)
	sqlStruck := db.SqlEmitUnlockStruct{}
	sqlStruck.DwUin = p.M_Player.M_DwUin
	sqlStruck.Value = str_concat
	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&sqlStruck, "t_player_emit_unlock", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&sqlStruck, "t_player_emit_unlock")
	}
	p.IsHaveDataDb = true
	return true
}

func (p *PlayerEmitUnlockData) ResPlayerEmitUnlockData(player *Player) {
	if player != p.M_Player {
		return
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResPlayerEmitUnlockData", data)
}

func (p *PlayerEmitUnlockData) NotifyDailyRenewEmitUnlock(param []interface{}) {
	p.Data.RenewTime = int32(param[0].(int64))
	for k := range p.Data.MEmitUnlockData {
		p.Data.MEmitUnlockData[k] = 0
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "NotifyDailyRenewEmitUnlock", data)
	// p.SaveDataFromDB("")
}

func (p *PlayerEmitUnlockData) UpdatePlayerEmitUnlockData(buf []byte) {

	update := &msg.UpdatePlayerEmitUnlockData{}
	proto.Unmarshal(buf, update)

	p.Data.MEmitUnlockData = update.MEmitUnlockData

	p.SaveDataFromDB("")
}

////////////////////////

type PlayerEmitPackData struct {
	*PlayerData
	Data msg.ResPlayerPackData
}

func (p *PlayerEmitPackData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_pack_data WHERE dwUin = ?"
	sqlStruck := db.SqlPackStruct{}
	p.Data.MPackData = make(map[int32]string)
	if err := db.SqlDb.Get(&sqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}

	if sqlStruck.MPackData != "" {
		arr := strings.Split(sqlStruck.MPackData, "_")

		for i := 0; i < len(arr); i++ {
			ss := strings.Split(arr[i], ";")
			id, err := strconv.ParseInt(ss[0], 10, 32)
			// ss1 := strings.Split(ss[1], ",")

			str := ss[1]

			if err != nil {
				panic(err)
			}

			p.Data.MPackData[int32(id)] = str
		}
	}

	p.Data.DwUin = dwUin.(int32)
	p.Reconnect(false)
	return true
}

func (p *PlayerEmitPackData) Reconnect(b bool) {

}

func (p *PlayerEmitPackData) SaveDataFromDB(Key interface{}) bool {
	var strarr []string
	for k, v := range p.Data.MPackData {
		str := fmt.Sprintf("%d;%s", k, v)
		strarr = append(strarr, str)
	}
	str_concat := strings.Join(strarr, "_")

	sqlStruck := db.SqlPackStruct{}
	sqlStruck.DwUin = p.M_Player.M_DwUin
	sqlStruck.MPackData = str_concat
	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&sqlStruck, "t_player_pack_data", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&sqlStruck, "t_player_pack_data")
	}
	p.IsHaveDataDb = true
	return true
}

func (p *PlayerEmitPackData) ResPlayerPackData(player *Player) {
	if player != p.M_Player {
		return
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResPlayerPackData", data)
}

func (p *PlayerEmitPackData) UpdatePlayerPackData(buf []byte) {

	update := &msg.UpdatePlayerPackData{}
	proto.Unmarshal(buf, update)

	p.Data.MPackData = update.MPackData

	p.SaveDataFromDB("")
}

func (p *PlayerEmitPackData) ClearData() bool {
	p.SaveDataFromDB("")

	return true
}

///////////////////////

type PlayerChessData struct {
	*PlayerData
	Data      msg.ResPlayerChessData
	ColorData msg.ResChessColorData
}

func (p *PlayerChessData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_chess_data WHERE dwUin = ?"
	sqlStruck := db.SqlChessStruct{}
	p.Data.MChessData = make(map[string]int32)
	p.ColorData.MChessColorData = make(map[string]int32)

	if err := db.SqlDb.Get(&sqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}

	if sqlStruck.MChessData != "" {
		arr := strings.Split(sqlStruck.MChessData, "_")

		for i := 0; i < len(arr); i++ {
			ss := strings.Split(arr[i], ",")
			id, err := strconv.ParseInt(ss[1], 10, 32)
			key := ss[0]

			if err != nil {
				panic(err)
			}

			p.Data.MChessData[key] = int32(id)
		}
	}
	if sqlStruck.MChessColorData != "" {
		arr := strings.Split(sqlStruck.MChessColorData, "_")

		for i := 0; i < len(arr); i++ {
			ss := strings.Split(arr[i], ",")
			id, err := strconv.ParseInt(ss[1], 10, 32)
			key := ss[0]

			if err != nil {
				panic(err)
			}

			p.ColorData.MChessColorData[key] = int32(id)
		}
	}

	p.Data.DwUin = dwUin.(int32)
	p.Reconnect(false)
	return true
}

func (p *PlayerChessData) Reconnect(b bool) {

}

func (p *PlayerChessData) SetValueByKey(k string) {
	if k != "" {
		p.Data.MChessData[k] = p.Data.MChessData[k] + 1
	}
}

func (p *PlayerChessData) GetValueByKey(k string) int32 {

	v, ok := p.Data.MChessData[k]
	if ok {
		return v
	}
	return -1
}
func (p *PlayerChessData) GetKeyByEmitID(EmitID int32) string {
	for k, _ := range p.Data.MChessData {
		units := strings.Split(k, "@")
		if len(units) >= 4 {
			n, _ := strconv.Atoi(units[3])
			if EmitID == int32(n) {
				return k
			}
		}
	}
	return ""
}

func (p *PlayerChessData) SaveDataFromDB(Key interface{}) bool {
	var strarr []string
	var strarr1 []string
	for k, v := range p.Data.MChessData {
		str := fmt.Sprintf("%s,%d", k, v)
		strarr = append(strarr, str)
	}
	str_concat := strings.Join(strarr, "_")

	for k, v := range p.ColorData.MChessColorData {
		str := fmt.Sprintf("%s,%d", k, v)
		strarr1 = append(strarr1, str)
	}
	str_concat1 := strings.Join(strarr1, "_")

	sqlStruck := db.SqlChessStruct{}
	sqlStruck.DwUin = p.M_Player.M_DwUin
	sqlStruck.MChessData = str_concat
	sqlStruck.MChessColorData = str_concat1
	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&sqlStruck, "t_player_chess_data", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&sqlStruck, "t_player_chess_data")
	}
	p.IsHaveDataDb = true
	return true
}

func (p *PlayerChessData) ResPlayerChessData(player *Player) {
	if player != p.M_Player {
		return
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResPlayerChessData", data)
}

func (p *PlayerChessData) ResChessColorData(player *Player) {
	if player != p.M_Player {
		return
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.ColorData)
	G_getGameLogic().PackResInfo(agent, "ResChessColorData", data)
}

func (p *PlayerChessData) UpdatePlayerChessData(buf []byte) {

	update := &msg.UpdatePlayerChessData{}
	proto.Unmarshal(buf, update)

	p.Data.MChessData = update.MChessData

	p.SaveDataFromDB("")
}

func (p *PlayerChessData) UpdateChessColorData(buf []byte) {

	update := &msg.UpdateChessColorData{}
	proto.Unmarshal(buf, update)

	p.ColorData.MChessColorData = update.MChessColorData

	p.SaveDataFromDB("")
}
func (p *PlayerChessData) GetChestKeyByValue(id int32) string {
	for k, v := range p.Data.MChessData {
		if id == v {
			return k
		}
	}
	return ""
}

func (p *PlayerChessData) ClearData() bool {
	p.SaveDataFromDB("")

	return true
}

///////////////////////

type PlayerGiftData struct {
	*PlayerData
	Data msg.ResPlayerGiftData
}

func (p *PlayerGiftData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_gift_data WHERE dwUin = ?"
	sqlStruck := db.SqlGiftStruct{}
	p.Data.MGiftData = make(map[int32]int32)
	if err := db.SqlDb.Get(&sqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}
	if sqlStruck.MGiftData != "" {
		arr := strings.Split(sqlStruck.MGiftData, "_")

		for i := 0; i < len(arr); i++ {
			ss := strings.Split(arr[i], ",")
			id, err := strconv.ParseInt(ss[1], 10, 32)
			key, _ := strconv.ParseInt(ss[0], 10, 32)

			if err != nil {
				panic(err)
			}

			p.Data.MGiftData[int32(key)] = int32(id)
		}
	}

	p.Data.DwUin = dwUin.(int32)
	p.Reconnect(false)
	return true
}

func (p *PlayerGiftData) Reconnect(b bool) {

}

func (p *PlayerGiftData) SaveDataFromDB(Key interface{}) bool {
	var strarr []string
	for k, v := range p.Data.MGiftData {
		str := fmt.Sprintf("%d,%d", k, v)
		strarr = append(strarr, str)
	}
	str_concat := strings.Join(strarr, "_")

	sqlStruck := db.SqlGiftStruct{}
	sqlStruck.DwUin = p.M_Player.M_DwUin
	sqlStruck.MGiftData = str_concat
	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&sqlStruck, "t_player_gift_data", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&sqlStruck, "t_player_gift_data")
	}
	p.IsHaveDataDb = true
	return true
}

func (p *PlayerGiftData) ResPlayerGiftData(player *Player) {
	if player != p.M_Player {
		return
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResPlayerGiftData", data)
}

func (p *PlayerGiftData) UpdatePlayerGiftData(buf []byte) {

	update := &msg.UpdatePlayerGiftData{}
	proto.Unmarshal(buf, update)

	p.Data.MGiftData = update.MGiftData

	p.SaveDataFromDB("")
}

func (p *PlayerGiftData) ClearData() bool {
	p.SaveDataFromDB("")

	return true
}

////////////
///////////////////////

type PlayerOrderData struct {
	*PlayerData
	Data       msg.ResPlayerOrderData
	misOrderCD bool
	Mdispatr   *timer.Dispatcher
	MLeafTimer *timer.Timer
}

func (p *PlayerOrderData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_order_data WHERE dwUin = ?"
	sqlStruck := db.SqlOrderStruct{}
	p.Data.MOrderData = make(map[int32]string)
	p.misOrderCD = false
	p.Mdispatr = timer.NewDispatcher(1)
	if err := db.SqlDb.Get(&sqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}
	if sqlStruck.MOrderData != "" {
		arr := strings.Split(sqlStruck.MOrderData, "_")

		for i := 0; i < len(arr); i++ {
			ss := strings.Split(arr[i], ",")
			key, _ := strconv.ParseInt(ss[0], 10, 32)
			final := strings.Join(ss[1:], ",")
			p.Data.MOrderData[int32(key)] = final
		}
	}

	p.Data.DwUin = dwUin.(int32)
	p.Data.FinishOrderCount = sqlStruck.FinishOrderCount
	p.Data.FinishOrderTime = sqlStruck.FinishOrderTime
	p.Data.RenewTime = sqlStruck.RenewTime

	p.Reconnect(false)

	return true
}
func (p *PlayerOrderData) Reconnect(b bool) {
	if p.Data.FinishOrderCount >= 5 && p.Data.FinishOrderTime == 0 {
		p.Data.FinishOrderCount = 0
		p.Data.FinishOrderTime = 0
	}
	if p.Data.FinishOrderTime > 0 && p.Data.FinishOrderCount >= 5 && p.Data.RenewTime <= p.Data.FinishOrderTime {

		deltaTime := p.Data.FinishOrderTime + 2*3600 - int32(time.Now().Unix())
		if deltaTime <= 0 {
			p.Data.FinishOrderCount = 0
			p.Data.RenewTime = p.Data.FinishOrderTime + 2*3600
			p.Data.FinishOrderTime = 0

			if b {
				p.NotifyDailyOrderRenew()
			}
		} else {
			p.misOrderCD = true
			go func() {
				// 注释内容也可以使用

				p.MLeafTimer = p.Mdispatr.AfterFunc(time.Duration(deltaTime)*time.Second, func() {
					p.NotifyDailyOrderRenew()
					p.MLeafTimer = nil
					p.misOrderCD = false
				})
				(<-p.Mdispatr.ChanTimer).Cb()
			}()
		}
	}
}

func (p *PlayerOrderData) ClearData() bool {
	p.SaveDataFromDB("")
	if p.MLeafTimer != nil {
		p.MLeafTimer.Disabled()
		p.Mdispatr.ChanTimer <- p.MLeafTimer
		p.MLeafTimer.Stop()
		p.MLeafTimer = nil
	}
	return true
}

func (p *PlayerOrderData) SaveDataFromDB(Key interface{}) bool {
	var strarr []string
	for k, v := range p.Data.MOrderData {
		str := fmt.Sprintf("%d,%s", k, v)
		strarr = append(strarr, str)
	}
	str_concat := strings.Join(strarr, "_")

	sqlStruck := db.SqlOrderStruct{}
	sqlStruck.DwUin = p.M_Player.M_DwUin
	sqlStruck.MOrderData = str_concat
	sqlStruck.FinishOrderCount = p.Data.FinishOrderCount
	sqlStruck.FinishOrderTime = p.Data.FinishOrderTime
	sqlStruck.RenewTime = p.Data.RenewTime
	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&sqlStruck, "t_player_order_data", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&sqlStruck, "t_player_order_data")
	}
	p.IsHaveDataDb = true
	return true
}

func (p *PlayerOrderData) ResPlayerOrderData(player *Player) {
	if player != p.M_Player {
		return
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResPlayerOrderData", data)
}

func (p *PlayerOrderData) UpdatePlayerOrderData(buf []byte) {

	update := &msg.UpdatePlayerOrderData{}
	proto.Unmarshal(buf, update)

	p.Data.MOrderData = update.MOrderData
	p.Data.FinishOrderCount = update.FinishOrderCount

	if p.misOrderCD == false && p.Data.FinishOrderCount >= 5 {
		p.Data.FinishOrderTime = int32(time.Now().Unix())
		p.misOrderCD = true
		go func() {
			// 注释内容也可以使用
			p.MLeafTimer = p.Mdispatr.AfterFunc(time.Duration(2*3600)*time.Second, func() {
				p.NotifyDailyOrderRenew()
				p.MLeafTimer = nil
				p.misOrderCD = false
			})
			(<-p.Mdispatr.ChanTimer).Cb()
		}()
	}

	p.SaveDataFromDB("")
}

func (p *PlayerOrderData) NotifyDailyOrderRenew() {

	notify := &msg.NotifyDailyOrderRenew{}
	notify.RenewTime = int32(time.Now().Unix())
	notify.FinishOrderCount = 0
	notify.FinishOrderTime = 0
	notify.DwUin = p.GetPlayer().M_DwUin
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyDailyOrderRenew", data)
	// p.SaveDataFromDB("")
}

/////////

type PlayerUnlockingChestData struct {
	*PlayerData
	Data       msg.ResUnlockingChestID
	MLeafTimer *timer.Timer
	Mdispatr   *timer.Dispatcher
}

func (p *PlayerUnlockingChestData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_chest_data WHERE dwUin = ?"
	sqlStruck := db.SqlChestStruct{}
	p.Mdispatr = timer.NewDispatcher(1)
	if err := db.SqlDb.Get(&sqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}
	p.Data.DwUin = dwUin.(int32)
	p.Data.ChestID = sqlStruck.ChestID
	p.Data.UnlockStartTime = sqlStruck.UnlockStartTime
	p.Data.CurSvrTime = int32(time.Now().Unix())

	p.Reconnect(false)
	return true
}
func (p *PlayerUnlockingChestData) Reconnect(b bool) {
	if p.Data.ChestID > 0 {
		chessKey := p.GetPlayer().GetIFGameData("PlayerChessData").(*PlayerChessData).GetKeyByEmitID(p.Data.ChestID)
		if chessKey == "" {
			p.Data.ChestID = 0
			p.Data.UnlockStartTime = 0
			return
		}
		MergeId := p.GetPlayer().GetIFGameData("PlayerChessData").(*PlayerChessData).GetValueByKey(chessKey)
		record := gamedata.GetConfigByName("MergeData").Index(int(MergeId))
		item := record.(*gamedata.MergeDataRecord)
		cool := item.CoolTime
		deltaTime := time.Now().Unix() - (int64)(p.Data.UnlockStartTime)
		if deltaTime >= (int64)(cool) { //注意后面读表
			if p.M_Player.GetGameData("PlayerChessData") == nil {
				data := &PlayerChessData{PlayerData: NewPlayerData("PlayerChessData", p.M_Player)}
				ok := data.LoadDataFromDB(p.M_Player.M_DwUin)
				if ok {
					p.M_Player.playerdata["PlayerChessData"] = data
					p.M_Player.playerdataIF["PlayerChessData"] = data
				}
			}

			p.GetPlayer().GetIFGameData("PlayerChessData").(*PlayerChessData).SetValueByKey(chessKey)
			fmt.Println("chessKey:", chessKey)
			p.Data.ChestID = 0
			p.Data.UnlockStartTime = 0
			if b {
				p.NotifyUnlockingChestData()
			}
		} else {
			go func() {
				// 注释内容也可以使用
				t1 := (int64)(cool) - deltaTime

				p.MLeafTimer = p.Mdispatr.AfterFunc(time.Duration(t1)*time.Second, func() {
					p.NotifyUnlockingChestData()
					p.MLeafTimer = nil
				})
				(<-p.Mdispatr.ChanTimer).Cb()
			}()
		}
		p.NotifyInitUnlockingChestID()
	}
}

func (p *PlayerUnlockingChestData) RenewData() {
	if p.Data.ChestID > 0 {
		chessKey := p.GetPlayer().GetIFGameData("PlayerChessData").(*PlayerChessData).GetKeyByEmitID(p.Data.ChestID)
		MergeId := p.GetPlayer().GetIFGameData("PlayerChessData").(*PlayerChessData).GetValueByKey(chessKey)
		// MergeId := p.M_Player.GetIFGameData("PlayerEmitDetaliData").(*PlayerEmitDetaliData).GetMergeIDByChestid(p.Data.ChestID)
		record := gamedata.GetConfigByName("MergeData").Index(int(MergeId))
		item := record.(*gamedata.MergeDataRecord)
		cool := item.CoolTime
		deltaTime := time.Now().Unix() - (int64)(p.Data.UnlockStartTime)
		if p.MLeafTimer != nil {
			p.MLeafTimer.Disabled()
			p.Mdispatr.ChanTimer <- p.MLeafTimer
			p.MLeafTimer.Stop()
			p.MLeafTimer = nil
		}
		if deltaTime >= (int64)(cool) { //注意后面读表

			p.GetPlayer().GetIFGameData("PlayerChessData").(*PlayerChessData).SetValueByKey(chessKey)

			p.Data.ChestID = 0
			p.Data.UnlockStartTime = 0
		} else {
			go func() {
				// 注释内容也可以使用
				t1 := (int64)(cool) - deltaTime

				p.MLeafTimer = p.Mdispatr.AfterFunc(time.Duration(t1)*time.Second, func() {
					p.NotifyUnlockingChestData()
					p.MLeafTimer = nil
				})
				(<-p.Mdispatr.ChanTimer).Cb()
			}()
		}
		p.NotifyInitUnlockingChestID()
	}
}

func (p *PlayerUnlockingChestData) NotifyInitUnlockingChestID() {
	notify := &msg.NotifyInitUnlockingChestID{}
	notify.ChestID = p.Data.ChestID
	notify.UnlockStartTime = p.Data.UnlockStartTime
	notify.DwUin = p.M_Player.M_DwUin
	notify.CurSvrTime = int32(time.Now().Unix())
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyInitUnlockingChestID", data)
}

func (p *PlayerUnlockingChestData) ClearData() bool {
	p.SaveDataFromDB("")
	if p.MLeafTimer != nil {
		p.MLeafTimer.Disabled()
		p.Mdispatr.ChanTimer <- p.MLeafTimer
		p.MLeafTimer.Stop()
		p.MLeafTimer = nil
	}
	return true
}
func (p *PlayerUnlockingChestData) SaveDataFromDB(Key interface{}) bool {

	sqlStruck := db.SqlChestStruct{}
	sqlStruck.DwUin = p.M_Player.M_DwUin
	sqlStruck.ChestID = p.Data.ChestID
	sqlStruck.UnlockStartTime = p.Data.UnlockStartTime

	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&sqlStruck, "t_player_chest_data", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&sqlStruck, "t_player_chest_data")
	}
	p.IsHaveDataDb = true
	return true
}

func (p *PlayerUnlockingChestData) ResUnlockingChestID(buf []byte) {
	update := &msg.ReqUnlockingChestID{}
	proto.Unmarshal(buf, update)
	p.Data.ChestID = update.ChestID
	p.Data.UnlockStartTime = int32(time.Now().Unix())
	// G_getGameLogic().Mlogger.Debug("ResUnlockingChestID1:", p.Data.ChestID, update.MergeID)
	p.M_Player.GetIFGameData("PlayerEmitDetaliData").(*PlayerEmitDetaliData).SetMergeIDByChestid(update.ChestID, update.MergeID)
	// G_getGameLogic().Mlogger.Debug("ResUnlockingChestID2:", p.Data.ChestID, update.MergeID)
	p.RenewData()
	// G_getGameLogic().Mlogger.Debug("ResUnlockingChestID3:", p.Data.ChestID, update.MergeID)
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResUnlockingChestID", data)
}

func (p *PlayerUnlockingChestData) ResChestUnlockCD(buf []byte) {
	update := &msg.ReqChestUnlockCD{}
	proto.Unmarshal(buf, update)

	res := &msg.ResChestUnlockCD{}
	res.DwUin = p.GetPlayer().M_DwUin
	res.ChestID = update.ChestID
	res.Type = update.Type
	res.CurSvrTime = int32(time.Now().Unix())
	////ad
	if res.Type == 3 {
		p.Data.UnlockStartTime = p.Data.UnlockStartTime - 60*30
		res.UnlockStartTime = p.Data.UnlockStartTime
		p.RenewData()
	}
	///diamond
	if res.Type == 2 {
		p.Data.UnlockStartTime = 0
		p.RenewData()
	}

	if res.Type == 1 {
		p.Data.ChestID = 0
		p.Data.UnlockStartTime = 0
		if p.MLeafTimer != nil {
			p.MLeafTimer.Disabled()
			p.Mdispatr.ChanTimer <- p.MLeafTimer
			p.MLeafTimer.Stop()
			p.MLeafTimer = nil
		}
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResChestUnlockCD", data)
}

func (p *PlayerUnlockingChestData) NotifyUnlockingChestData() {

	chessKey := p.GetPlayer().GetIFGameData("PlayerChessData").(*PlayerChessData).GetKeyByEmitID(p.Data.ChestID)
	p.GetPlayer().GetIFGameData("PlayerChessData").(*PlayerChessData).SetValueByKey(chessKey)

	notify := &msg.NotifyUnlockingChestData{}
	notify.DwUin = p.GetPlayer().M_DwUin
	notify.ChestID = 0
	notify.UnlockStartTime = 0
	p.Data.ChestID = 0
	p.Data.UnlockStartTime = 0
	notify.CurSvrTime = int32(time.Now().Unix())

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyUnlockingChestData", data)

}

//////////////////////////////////

/////////

type PlayerEmitDetaliData struct {
	*PlayerData
	Data      msg.ResEmitMergeMap
	CountData msg.ResEmitCountMap
	TimeData  msg.ResEmitCDStartData
	// MLeafTimerList map[int32]*timer.Timer
	MLeafTimerList cmap.ConcurrentMap[string, *timer.Timer]
	Mdispatr       *timer.Dispatcher
}

func (p *PlayerEmitDetaliData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_Emit_detail_data WHERE dwUin = ?"
	sqlStruck := db.SqlEmitStruct{}
	p.Mdispatr = timer.NewDispatcher(1)
	p.Data.MEmitMergeData = make(map[int32]int32)
	p.CountData.MEmitCountData = make(map[int32]int32)
	p.TimeData.MEmitCDData = make(map[int32]int32)
	// p.MLeafTimerList = make(map[int32]*timer.Timer)
	p.MLeafTimerList = cmap.New[*timer.Timer]()
	if err := db.SqlDb.Get(&sqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}
	if sqlStruck.MEmitMergeData != "" {
		units := strings.Split(sqlStruck.MEmitMergeData, "_")
		for i := 0; i < len(units); i++ {
			unit := units[i]
			ss := strings.Split(unit, ",")
			key, _ := strconv.ParseInt(ss[0], 10, 32)
			value, _ := strconv.ParseInt(ss[1], 10, 32)
			p.Data.MEmitMergeData[int32(key)] = int32(value)
		}
	}
	if sqlStruck.MEmitCountData != "" {
		units1 := strings.Split(sqlStruck.MEmitCountData, "_")
		for i := 0; i < len(units1); i++ {
			unit := units1[i]
			ss := strings.Split(unit, ",")
			key, _ := strconv.ParseInt(ss[0], 10, 32)
			value, _ := strconv.ParseInt(ss[1], 10, 32)
			p.CountData.MEmitCountData[int32(key)] = int32(value)
		}
	}
	if sqlStruck.MEmitTimeData != "" {
		units2 := strings.Split(sqlStruck.MEmitTimeData, "_")
		for i := 0; i < len(units2); i++ {
			unit := units2[i]
			ss := strings.Split(unit, ",")
			key, _ := strconv.ParseInt(ss[0], 10, 32)
			value, _ := strconv.ParseInt(ss[1], 10, 32)
			p.TimeData.MEmitCDData[int32(key)] = int32(value)
		}
	}
	tempMap := make(map[int32]int32)
	isDelete := false
	for k, v := range p.TimeData.MEmitCDData {
		MergeId := p.GetMergeIDByChestid(k)
		if int(MergeId) != 0 {
			tempMap[k] = v
		} else {
			isDelete = true
		}
	}
	p.TimeData.MEmitCDData = tempMap
	if isDelete {
		p.SaveDataFromDB("")
	}

	p.Reconnect(false)

	return true
}

func (p *PlayerEmitDetaliData) Reconnect(b bool) {
	for k, v := range p.TimeData.MEmitCDData {
		MergeId := p.GetMergeIDByChestid(k)
		record := gamedata.GetConfigByName("MergeData").Index(int(MergeId))
		item := record.(*gamedata.MergeDataRecord)
		cnt := p.M_Player.GetIFGameData("PlayerEmitUnlockData").(*PlayerEmitUnlockData).GetUnlockCntByID(k)
		cool := float32(item.CoolTime)*(1.0+0.2*float32(cnt)) + float32(v)
		deltaTime := int32(cool) - int32(time.Now().Unix())
		if deltaTime > 0 {
			EmitID := k
			go func() {

				LeafTimer := p.Mdispatr.AfterFunc(time.Duration(deltaTime)*time.Second, func() {
					p.NotifyEmitCDTimeEndData(EmitID)
					// delete(p.MLeafTimerList, EmitID)
					p.MLeafTimerList.Remove(strconv.Itoa(int(EmitID)))
				})
				// p.MLeafTimerList[EmitID] = LeafTimer
				p.MLeafTimerList.Set(strconv.Itoa(int(EmitID)), LeafTimer)
				(<-p.Mdispatr.ChanTimer).Cb()
			}()
		} else {
			delete(p.TimeData.MEmitCDData, k)
		}

	}
	p.NotifyInitEmitCDTimeData()
}

func (p *PlayerEmitDetaliData) NotifyInitEmitCDTimeData() {
	notify := &msg.NotifyInitEmitCDTimeData{}
	notify.MEmitCDData = make(map[int32]int32)
	notify.MEmitCDData = p.TimeData.MEmitCDData

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyInitEmitCDTimeData", data)
}

func (p *PlayerEmitDetaliData) NotifyEmitCDTimeEndData(EmitID int32) {
	notify := &msg.NotifyEmitCDTimeEndData{}
	notify.MEmitCDData = make(map[int32]int32)
	notify.MEmitCDData[EmitID] = 0

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyEmitCDTimeEndData", data)
}

func (p *PlayerEmitDetaliData) ClearEmitCD(id int32) {

}

func (p *PlayerEmitDetaliData) ClearAllEmitCD() {

	for k, _ := range p.TimeData.MEmitCDData {
		p.TimeData.MEmitCDData[k] = 0
		p.ClearEmitCD(k)
	}
	keys := p.MLeafTimerList.Keys()
	for _, k := range keys {
		v, _ := p.MLeafTimerList.Get(k)
		v.Disabled()
		p.Mdispatr.ChanTimer <- v
		v.Stop()
	}
	p.MLeafTimerList.Clear()
	for k := range p.TimeData.MEmitCDData {
		delete(p.TimeData.MEmitCDData, k)
	}

	p.NotifyInitEmitCDTimeData()
}

func (p *PlayerEmitDetaliData) ReqEmitSubCD(buf []byte) {
	update := &msg.ReqEmitSubCD{}
	proto.Unmarshal(buf, update)

	_, ok := p.TimeData.MEmitCDData[update.EmitID]
	if ok {
		if update.Type == 3 {
			p.TimeData.MEmitCDData[update.EmitID] = p.TimeData.MEmitCDData[update.EmitID] - 60*30
		}
		///diamond
		if update.Type == 2 {
			p.TimeData.MEmitCDData[update.EmitID] = 0
		}
		///diamond
		if update.Type == 4 {
			p.TimeData.MEmitCDData[update.EmitID] = 0
		}
		if update.Type == 1 {
			p.TimeData.MEmitCDData[update.EmitID] = 0
		}
	}
	////ad
	keys := p.MLeafTimerList.Keys()
	for _, k := range keys {
		v, _ := p.MLeafTimerList.Get(k)
		v.Disabled()
		p.Mdispatr.ChanTimer <- v
		v.Stop()
	}
	p.MLeafTimerList.Clear()

	for k, v := range p.TimeData.MEmitCDData {
		MergeId := p.GetMergeIDByChestid(k)
		record := gamedata.GetConfigByName("MergeData").Index(int(MergeId))
		item := record.(*gamedata.MergeDataRecord)
		cnt := p.M_Player.GetIFGameData("PlayerEmitUnlockData").(*PlayerEmitUnlockData).GetUnlockCntByID(k)
		cool := float32(item.CoolTime)*(1.0+0.2*float32(cnt)) + float32(v)
		deltaTime := int32(cool) - int32(time.Now().Unix())
		if deltaTime > 0 {
			EmitID := k
			go func() {
				LeafTimer := p.Mdispatr.AfterFunc(time.Duration(deltaTime)*time.Second, func() {
					p.NotifyEmitCDTimeEndData(EmitID)
					p.MLeafTimerList.Remove(strconv.Itoa(int(EmitID)))
				})
				p.MLeafTimerList.Set(strconv.Itoa(int(EmitID)), LeafTimer)
				(<-p.Mdispatr.ChanTimer).Cb()
			}()
		} else {
			delete(p.TimeData.MEmitCDData, k)
		}
	}
	p.NotifyInitEmitCDTimeData()
}

func (p *PlayerEmitDetaliData) ClearData() bool {
	p.SaveDataFromDB("")
	keys := p.MLeafTimerList.Keys()
	for _, k := range keys {
		v, _ := p.MLeafTimerList.Get(k)
		v.Disabled()
		p.Mdispatr.ChanTimer <- v
		v.Stop()
	}
	p.MLeafTimerList.Clear()
	// for _, v := range p.MLeafTimerList {
	// 	v.Disabled()
	// 	p.Mdispatr.ChanTimer <- v
	// 	v.Stop()
	// }
	// for k := range p.MLeafTimerList {
	// 	delete(p.MLeafTimerList, k)
	// }

	return true
}
func (p *PlayerEmitDetaliData) SaveDataFromDB(Key interface{}) bool {

	sqlStruck := db.SqlEmitStruct{}
	sqlStruck.DwUin = p.M_Player.M_DwUin
	strarr := []string{}
	strarr1 := []string{}
	strarr2 := []string{}
	for k, v := range p.Data.MEmitMergeData {
		str := fmt.Sprintf("%d,%d", k, v)
		strarr = append(strarr, str)
	}
	for k, v := range p.CountData.MEmitCountData {
		str := fmt.Sprintf("%d,%d", k, v)
		strarr1 = append(strarr1, str)
	}
	for k, v := range p.TimeData.MEmitCDData {
		str := fmt.Sprintf("%d,%d", k, v)
		strarr2 = append(strarr2, str)
	}
	str_concat := strings.Join(strarr, "_")
	str_concat1 := strings.Join(strarr1, "_")
	str_concat2 := strings.Join(strarr2, "_")

	sqlStruck.MEmitMergeData = str_concat
	sqlStruck.MEmitCountData = str_concat1
	sqlStruck.MEmitTimeData = str_concat2

	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&sqlStruck, "t_Emit_detail_data", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&sqlStruck, "t_Emit_detail_data")
	}
	p.IsHaveDataDb = true
	return true
}

func (p *PlayerEmitDetaliData) GetMergeIDByChestid(emitId int32) int32 {
	_, ok := p.Data.MEmitMergeData[emitId]
	if ok {
		return p.Data.MEmitMergeData[emitId]
	}
	return 0
}

func (p *PlayerEmitDetaliData) SetMergeIDByChestid(emitId int32, MergeId int32) {

	p.Data.MEmitMergeData[emitId] = MergeId

}

func (p *PlayerEmitDetaliData) ResEmitMergeMap(buf []byte) {
	update := &msg.ReqEmitMergeMap{}
	proto.Unmarshal(buf, update)

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResEmitMergeMap", data)
}

func (p *PlayerEmitDetaliData) ResEmitCountMap(buf []byte) {
	update := &msg.ReqEmitCountMap{}
	proto.Unmarshal(buf, update)

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.CountData)
	G_getGameLogic().PackResInfo(agent, "ResEmitCountMap", data)
}

func (p *PlayerEmitDetaliData) ResEmitCDStartData(buf []byte) {
	update := &msg.ReqEmitCDStartData{}
	proto.Unmarshal(buf, update)

	MergeId := p.GetMergeIDByChestid(update.EmitID)
	record := gamedata.GetConfigByName("MergeData").Index(int(MergeId))
	item := record.(*gamedata.MergeDataRecord)
	CurTime := time.Now().Unix()

	cnt := p.M_Player.GetIFGameData("PlayerEmitUnlockData").(*PlayerEmitUnlockData).GetUnlockCntByID(update.EmitID)
	deltaTime := float32(item.CoolTime) * (1.0 + 0.2*float32(cnt))
	if deltaTime > 0 {
		EmitID := update.EmitID
		go func() {

			LeafTimer := p.Mdispatr.AfterFunc(time.Duration(int32(deltaTime))*time.Second, func() {
				p.NotifyEmitCDTimeEndData(EmitID)
				// delete(p.MLeafTimerList, EmitID)
				p.MLeafTimerList.Remove(strconv.Itoa(int(EmitID)))
			})
			// p.MLeafTimerList[EmitID] = LeafTimer
			p.MLeafTimerList.Set(strconv.Itoa(int(EmitID)), LeafTimer)
			(<-p.Mdispatr.ChanTimer).Cb()
		}()
		p.TimeData.MEmitCDData[EmitID] = int32(CurTime)
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.TimeData)
	G_getGameLogic().PackResInfo(agent, "ResEmitCDStartData", data)
}

func (p *PlayerEmitDetaliData) UpdateEmitCountMap(buf []byte) {
	update := &msg.UpdateEmitCountMap{}
	proto.Unmarshal(buf, update)

	p.CountData.MEmitCountData = update.MEmitCountData
	p.SaveDataFromDB("")
}

func (p *PlayerEmitDetaliData) UpdateEmitMergeMap(buf []byte) {
	update := &msg.UpdateEmitMergeMap{}
	proto.Unmarshal(buf, update)

	p.Data.MEmitMergeData = update.MEmitMergeData
	p.SaveDataFromDB("")
}

//////////////////////////////////

type PlayerDecorateData struct {
	*PlayerData
	Data msg.ResDecorateData
}

func (p *PlayerDecorateData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_decorate_data WHERE dwUin = ?"
	sqlStruck := db.SqlDecorateStruct{}
	p.Data.MDecorateData = make(map[string]int32)
	p.Data.MFinishList = []int32{}
	if err := db.SqlDb.Get(&sqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}
	if sqlStruck.MDecorateData != "" {
		units := strings.Split(sqlStruck.MDecorateData, "_")
		for i := 0; i < len(units); i++ {
			unit := units[i]
			ss := strings.Split(unit, ",")
			key := ss[0]
			value, _ := strconv.ParseInt(ss[1], 10, 32)
			p.Data.MDecorateData[key] = int32(value)
		}
	}
	if sqlStruck.MFinishList != "" {
		units1 := strings.Split(sqlStruck.MFinishList, "_")
		for i := 0; i < len(units1); i++ {
			value, _ := strconv.ParseInt(units1[i], 10, 32)
			p.Data.MFinishList = append(p.Data.MFinishList, int32(value))
		}
	}

	return true
}
func (p *PlayerDecorateData) Reconnect(b bool) {

}

func (p *PlayerDecorateData) ClearData() bool {
	p.SaveDataFromDB("")

	return true
}
func (p *PlayerDecorateData) SaveDataFromDB(Key interface{}) bool {

	sqlStruck := db.SqlDecorateStruct{}
	sqlStruck.DwUin = p.M_Player.M_DwUin
	strarr := []string{}
	strarr1 := []string{}

	for k, v := range p.Data.MDecorateData {
		str := fmt.Sprintf("%s,%d", k, v)
		strarr = append(strarr, str)
	}
	for _, v := range p.Data.MFinishList {
		str := fmt.Sprintf("%d", v)
		strarr1 = append(strarr1, str)
	}

	str_concat := strings.Join(strarr, "_")
	str_concat1 := strings.Join(strarr1, "_")

	sqlStruck.MDecorateData = str_concat
	sqlStruck.MFinishList = str_concat1

	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&sqlStruck, "t_player_decorate_data", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&sqlStruck, "t_player_decorate_data")
	}
	p.IsHaveDataDb = true
	return true
}

func (p *PlayerDecorateData) ResDecorateData(player *Player) {

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResDecorateData", data)
}

func (p *PlayerDecorateData) UpdateDecorateData(buf []byte) {

	update := &msg.UpdateDecorateData{}
	proto.Unmarshal(buf, update)

	p.Data.MDecorateData = update.MDecorateData
	p.Data.MFinishList = update.MFinishList

	p.SaveDataFromDB("")
}

////////////////////////

type PlayerLevelUpPackData struct {
	*PlayerData
	Data msg.ResLevelUpPackInfo
}

func (p *PlayerLevelUpPackData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_lv_Pack WHERE dwUin = ?"
	sqlStruck := db.SqlLevelUpPackStruct{}
	sqlStruck.CurBuyedLv = 0
	if err := db.SqlDb.Get(&sqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}
	p.Data.DwUin = p.M_Player.M_DwUin
	p.Data.CurBuyLv = sqlStruck.CurBuyedLv
	return true
}
func (p *PlayerLevelUpPackData) Reconnect(b bool) {

}

func (p *PlayerLevelUpPackData) ClearData() bool {
	p.SaveDataFromDB("")

	return true
}
func (p *PlayerLevelUpPackData) SaveDataFromDB(Key interface{}) bool {

	sqlStruck := db.SqlLevelUpPackStruct{}
	sqlStruck.DwUin = p.M_Player.M_DwUin
	sqlStruck.CurBuyedLv = p.Data.CurBuyLv

	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&sqlStruck, "t_player_lv_Pack", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&sqlStruck, "t_player_lv_Pack")
	}
	p.IsHaveDataDb = true
	return true
}

func (p *PlayerLevelUpPackData) ResLevelUpPackInfo(player *Player) {

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResLevelUpPackInfo", data)
}

func (p *PlayerLevelUpPackData) ReqBuyLevelUpPack(buf []byte) {
	req := &msg.ReqBuyLevelUpPack{}
	res := &msg.ResBuyLevelUpPack{}
	proto.Unmarshal(buf, req)

	list := gamedata.GetConfigByName("LevelUpBuyPack").Indexes(1)
	recode, ok := list[int(req.CurBuyLv)]
	if ok {
		if req.CurBuyLv <= p.Data.CurBuyLv {
			res.ResultCode = MergeConst.Protocol_LvUpPack_Buyed
		} else {
			recode = recode.(*gamedata.LevelUpPackRecord)
			res.ResultCode = 0
			res.CurBuyLv = req.CurBuyLv
			p.Data.CurBuyLv = req.CurBuyLv
			p.SaveDataFromDB("")
		}
	} else {
		res.ResultCode = MergeConst.Protocol_LvUpPack_No_Exsit
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResBuyLevelUpPack", data)
}

////////////////////////

type PlayerGrowthFundData struct {
	*PlayerData
	Data msg.ResGrowthFundInfo
}

func (p *PlayerGrowthFundData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_growth_fund WHERE dwUin = ?"
	sqlStruck := db.SqlGrowthFundStruct{}
	sqlStruck.CurBuyLv = ""
	sqlStruck.IsBuy = 0
	if err := db.SqlDb.Get(&sqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}
	p.Data.DwUin = p.M_Player.M_DwUin
	p.Data.CurBuyLv = sqlStruck.CurBuyLv
	p.Data.IsBuy = sqlStruck.IsBuy
	return true
}
func (p *PlayerGrowthFundData) Reconnect(b bool) {

}

func (p *PlayerGrowthFundData) ClearData() bool {
	p.SaveDataFromDB("")

	return true
}
func (p *PlayerGrowthFundData) SaveDataFromDB(Key interface{}) bool {

	sqlStruck := db.SqlGrowthFundStruct{}
	sqlStruck.DwUin = p.M_Player.M_DwUin
	sqlStruck.CurBuyLv = p.Data.CurBuyLv
	sqlStruck.IsBuy = p.Data.IsBuy
	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&sqlStruck, "t_player_growth_fund", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&sqlStruck, "t_player_growth_fund")
	}
	p.IsHaveDataDb = true
	return true
}

func (p *PlayerGrowthFundData) ResGrowthFundInfo(player *Player) {

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResGrowthFundInfo", data)
}

func (p *PlayerGrowthFundData) ReqBuyGrowthFund(buf []byte) {
	req := &msg.ReqBuyGrowthFund{}
	res := &msg.ResBuyGrowthFund{}
	proto.Unmarshal(buf, req)

	p.Data.IsBuy = 1
	res.ResultCode = 0
	p.SaveDataFromDB("")

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResBuyGrowthFund", data)
}

func (p *PlayerGrowthFundData) ReqGetGrowthFundWard(buf []byte) {
	req := &msg.ReqGetGrowthFundWard{}
	res := &msg.ResGetGrowthFundWard{}
	proto.Unmarshal(buf, req)

	res.ResultCode = 0
	res.CurBuyLv = req.CurBuyLv
	isGet := false
	if p.Data.CurBuyLv != "" {
		units := strings.Split(p.Data.CurBuyLv, ",")
		for i := 0; i < len(units); i++ {
			con, _ := strconv.Atoi(units[i])
			if con == int(req.CurBuyLv) {
				isGet = true
				break
			}
		}
	}

	if !isGet {
		res.ResultCode = 0
		if p.Data.CurBuyLv == "" {
			p.Data.CurBuyLv = strconv.Itoa(int(req.CurBuyLv))
		} else {
			p.Data.CurBuyLv = p.Data.CurBuyLv + "," + strconv.Itoa(int(req.CurBuyLv))
		}

	} else {
		res.ResultCode = MergeConst.Protocol_GrowthFund_Geted
	}
	p.SaveDataFromDB("")

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResGetGrowthFundWard", data)
}

////////////////////////

type PlayerSupermeGiftData struct {
	*PlayerData
	Data        msg.ResSupremeGiftInfo
	Mdispatr    *timer.Dispatcher
	MLeafTimer  *timer.Timer
	MLeafTimer1 *timer.Timer
}

func (p *PlayerSupermeGiftData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_supremeGift_data WHERE dwUin = ?"
	sqlStruck := db.SqlSupermeGiftStruct{}

	sqlStruck.IsBuy = 0
	if err := db.SqlDb.Get(&sqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}
	p.Data.DwUin = p.M_Player.M_DwUin

	p.Data.IsBuy = sqlStruck.IsBuy
	p.Data.NoAdStartTime = sqlStruck.NoAdStartTime
	p.Data.NoAdEndTime = sqlStruck.NoAdEndTime
	p.Data.StorgeEndTime = sqlStruck.StorgeEndTime
	p.Data.StorgeStartTime = sqlStruck.StorgeStartTime
	p.Mdispatr = timer.NewDispatcher(2)
	p.Reconnect(false)
	return true
}

func (p *PlayerSupermeGiftData) CreateTimer() {

	curSvrTime := int32(time.Now().Unix())
	if p.Data.NoAdEndTime > curSvrTime {
		go func() {
			// 注释内容也可以使用
			t1 := (p.Data.NoAdEndTime) - curSvrTime

			p.MLeafTimer = p.Mdispatr.AfterFunc(time.Duration(t1)*time.Second, func() {

				p.NotifySupremeGiftTimeOver(1)
				p.MLeafTimer = nil

			})

			(<-p.Mdispatr.ChanTimer).Cb()

		}()
	}
	if p.Data.StorgeEndTime > curSvrTime {
		go func() {
			// 注释内容也可以使用
			t1 := (p.Data.StorgeEndTime) - curSvrTime

			p.MLeafTimer1 = p.Mdispatr.AfterFunc(time.Duration(t1)*time.Second, func() {
				p.NotifySupremeGiftTimeOver(2)
				p.MLeafTimer1 = nil
			})
			(<-p.Mdispatr.ChanTimer).Cb()
		}()
	}

}

func (p *PlayerSupermeGiftData) Reconnect(b bool) {

	p.CreateTimer()

}

func (p *PlayerSupermeGiftData) ClearData() bool {
	p.SaveDataFromDB("")
	if p.MLeafTimer != nil {
		p.MLeafTimer.Stop()
		p.MLeafTimer = nil
	}
	if p.MLeafTimer1 != nil {
		p.MLeafTimer1.Stop()
		p.MLeafTimer1 = nil
	}
	return true
}
func (p *PlayerSupermeGiftData) SaveDataFromDB(Key interface{}) bool {

	sqlStruck := db.SqlSupermeGiftStruct{}
	sqlStruck.DwUin = p.M_Player.M_DwUin
	sqlStruck.NoAdStartTime = p.Data.NoAdStartTime
	sqlStruck.NoAdEndTime = p.Data.NoAdEndTime
	sqlStruck.StorgeStartTime = p.Data.StorgeStartTime
	sqlStruck.StorgeEndTime = p.Data.StorgeEndTime
	sqlStruck.IsBuy = p.Data.IsBuy

	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&sqlStruck, "t_player_supremeGift_data", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&sqlStruck, "t_player_supremeGift_data")
	}
	p.IsHaveDataDb = true
	return true
}

func (p *PlayerSupermeGiftData) ResSupremeGiftInfo(player *Player) {

	p.Data.CurSvrTime = int32(time.Now().Unix())
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResSupremeGiftInfo", data)
}

func (p *PlayerSupermeGiftData) ReqBuySupremeGift(buf []byte) {
	req := &msg.ReqBuySupremeGift{}
	res := &msg.ResBuySupremeGift{}
	proto.Unmarshal(buf, req)

	res.ResultCode = 0
	res.NoAdStartTime = int32(time.Now().Unix())
	res.NoAdEndTime = res.NoAdStartTime + 3600*24

	res.StorgeStartTime = res.NoAdStartTime
	res.StorgeEndTime = res.StorgeStartTime + 3600*24
	res.CurSvrTime = res.NoAdStartTime

	p.Data.IsBuy = 1
	p.Data.NoAdStartTime = res.NoAdStartTime
	p.Data.NoAdEndTime = res.NoAdStartTime + 3600*24

	p.Data.StorgeStartTime = res.NoAdStartTime
	p.Data.StorgeEndTime = res.StorgeStartTime + 3600*24
	p.Data.CurSvrTime = res.NoAdStartTime

	p.SaveDataFromDB("")
	p.CreateTimer()
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResBuySupremeGift", data)
}

func (p *PlayerSupermeGiftData) NotifySupremeGiftTimeOver(type1 int32) {
	notify := &msg.NotifySupremeGiftTimeOver{}
	notify.Type = type1
	notify.CurSvrTime = int32(time.Now().Unix())

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifySupremeGiftTimeOver", data)
}

/////////////////////////////////////////////

type PlayerIllustrateData struct {
	*PlayerData
	Data       msg.ResIllustratedInfo
	sqlStrucks []db.SqlIllustrateStruct
}

func (p *PlayerIllustrateData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_illustrated_data WHERE dwUin = ?"
	p.sqlStrucks = []db.SqlIllustrateStruct{}

	if err := db.SqlDb.Select(&p.sqlStrucks, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}
	p.Data.DwUin = p.M_Player.M_DwUin
	p.Data.Datas = []*msg.CategoryIllustratedData{}

	for i := 0; i < len(p.sqlStrucks); i++ {
		data := msg.CategoryIllustratedData{}
		data.Category = p.sqlStrucks[i].Category
		data.Items = []*msg.SingleIllustratedItem{}
		data.IllustratedID = p.sqlStrucks[i].IllustratedID
		str := p.sqlStrucks[i].ItemInfoStr
		if str != "" {
			MergeInfo := strings.Split(str, ";")
			for m := 0; m < len(MergeInfo); m++ {
				item := MergeInfo[m]
				units := strings.Split(item, ",")
				single := msg.SingleIllustratedItem{}
				MergeId, _ := strconv.Atoi(units[0])
				Status, _ := strconv.Atoi(units[1])
				single.MergeId = int32(MergeId)
				single.Status = int32(Status)
				data.Items = append(data.Items, &single)
			}
		}
		p.Data.Datas = append(p.Data.Datas, &data)
	}
	p.Reconnect(false)
	return true
}

func (p *PlayerIllustrateData) Reconnect(b bool) {

}

func (p *PlayerIllustrateData) ClearData() bool {
	p.SaveDataFromDB("")

	return true
}

func (p *PlayerIllustrateData) SaveDataFromDBSingle(Category string, isUpdate bool) {

	// dbs db.SqlIllustrateStruct

	data := p.FindIllustratedDataByCategory(Category)
	sqlStruck := db.SqlIllustrateStruct{}
	sqlStruck.Category = Category
	sqlStruck.DwUin = p.M_Player.M_DwUin
	sqlStruck.IllustrateType = 1
	sqlStruck.IllustratedID = data.IllustratedID
	sqlStruck.ItemInfoStr = ""

	finalStr := []string{}
	for i := 0; i < len(data.Items); i++ {
		temp := strconv.Itoa(int(data.Items[i].MergeId)) + "," + strconv.Itoa(int(data.Items[i].Status))
		finalStr = append(finalStr, temp)
	}

	sqlStruck.ItemInfoStr = strings.Join(finalStr, ";")
	if isUpdate {
		db.FormatAllMemUpdateDb(&sqlStruck, "t_player_illustrated_data", "IllustratedID")
	} else {
		insertID, _ := db.FormatAllMemInsertDb(&sqlStruck, "t_player_illustrated_data")
		data.IllustratedID = int32(insertID)
	}
}

func (p *PlayerIllustrateData) SaveDataFromDB(Key interface{}) bool {

	return true
}

func (p *PlayerIllustrateData) ResIllustratedInfo(player *Player) {

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResIllustratedInfo", data)
}

func (p *PlayerIllustrateData) FindIllustratedDataByCategory(Category string) *msg.CategoryIllustratedData {
	for i := 0; i < len(p.Data.Datas); i++ {
		if p.Data.Datas[i].Category == Category {
			return p.Data.Datas[i]
		}
	}
	return nil
}

func (p *PlayerIllustrateData) FindMergeInfoById(mergeId int32, data *msg.CategoryIllustratedData) *msg.SingleIllustratedItem {
	for i := 0; i < len(data.Items); i++ {
		if mergeId == data.Items[i].MergeId {
			return data.Items[i]
		}
	}
	return nil
}

func (p *PlayerIllustrateData) ReqGetIllustrateItemReward(buf []byte) {
	req := &msg.ReqGetIllustrateItemReward{}
	res := &msg.ResGetIllustrateItemReward{}
	proto.Unmarshal(buf, req)

	res.ResultCode = 0
	res.Category = req.Category
	data := p.FindIllustratedDataByCategory(req.Category)
	if data == nil {
		res.ResultCode = MergeConst.Protocol_Illustrate_InActive
	} else {
		Item := p.FindMergeInfoById(req.MergeId, data)
		if Item != nil {
			if Item.Status == 1 {
				res.ResultCode = MergeConst.Protocol_Illustrate_InActive
			}
			if Item.Status == 3 {
				res.ResultCode = MergeConst.Protocol_Illustrate_Geted
			}
			if Item.Status == 2 {
				res.ResultCode = 0
				res.Status = 3
				res.MergeId = req.MergeId
				Item.Status = 3
				p.SaveDataFromDBSingle(req.Category, true)
			}
		} else {
			res.ResultCode = MergeConst.Protocol_Illustrate_InActive
		}

	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data1, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResGetIllustrateItemReward", data1)
}

func (p *PlayerIllustrateData) UpdateIllustrateItem(buf []byte) {
	update := &msg.UpdateIllustrateItem{}
	proto.Unmarshal(buf, update)
	data := p.FindIllustratedDataByCategory(update.Category)
	if data != nil {
		Item := p.FindMergeInfoById(update.MergeId, data)
		if Item != nil {
			Item.Status = update.Status
		} else {
			item := &msg.SingleIllustratedItem{}
			item.MergeId = update.MergeId
			item.Status = update.Status
			data.Items = append(data.Items, item)
		}
		p.SaveDataFromDBSingle(update.Category, true)
	} else {
		newdata := &msg.CategoryIllustratedData{}
		newdata.Category = update.Category
		newdata.IllustratedID = 0
		newdata.Items = []*msg.SingleIllustratedItem{}
		item := &msg.SingleIllustratedItem{}
		item.MergeId = update.MergeId
		item.Status = update.Status
		newdata.Items = append(newdata.Items, item)
		p.Data.Datas = append(p.Data.Datas, newdata)
		p.SaveDataFromDBSingle(update.Category, false)
	}

}

//////////////////////////////

type PlayerDailyTaskData struct {
	*PlayerData
	Data       msg.ResDailyTaskData
	sqlStruck  db.SqlDailyTaskStruct
	Mdispatr   *timer.Dispatcher
	MLeafTimer *timer.Timer
	MTicker    *time.Ticker
	// MLeafTimer1 *timer.Timer
}

func (p *PlayerDailyTaskData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_daily_task_data WHERE dwUin = ?"

	p.Data.TodayTaskList = []string{}
	p.sqlStruck = db.SqlDailyTaskStruct{}
	p.sqlStruck.DwUin = dwUin.(int32)
	if err := db.SqlDb.Get(&p.sqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}

	p.Data.DwUin = p.sqlStruck.DwUin
	p.Data.NowSortId = p.sqlStruck.NowSortId
	p.Data.NowTaskProgress = p.sqlStruck.NowTaskProgress
	p.Data.WeekActive = p.sqlStruck.WeekyActive
	p.Data.CurSvrTime = int32(time.Now().Unix())
	if p.sqlStruck.TodayTaskList != "" {
		strarr := strings.Split(p.sqlStruck.TodayTaskList, ";")

		for i := 0; i < len(strarr); i++ {
			p.Data.TodayTaskList = append(p.Data.TodayTaskList, strarr[i])
		}
	}

	p.Mdispatr = timer.NewDispatcher(1)
	p.Reconnect(false)
	return true
}

func (p *PlayerDailyTaskData) Notify_Daily_Renew(param []interface{}) {
	p.NotifyRenewDailyTask()
}

func (p *PlayerDailyTaskData) CreateTimer() {

	timeStamp := time.Now().Unix()
	t := time.Unix(timeStamp, 0).Local()
	// zero := timeStamp - (int64)(t.Hour()*3600+t.Minute()*60+t.Second())
	var week = t.Weekday()
	if t.Weekday() == 0 {
		week = 7
	}
	go func() {
		// 注释内容也可以使用
		p.MLeafTimer = p.Mdispatr.AfterFunc(time.Duration(3600*24*7-(int32)(week-1)*3600*24-(int32)(t.Hour()*3600+t.Minute()*60+t.Second()))*time.Second, func() {
			p.NotifyRenewWeekyActive()
			p.MLeafTimer = nil

			p.MTicker = time.NewTicker(time.Second * time.Duration(3600*24*7))
			for {
				select {
				case <-p.MTicker.C:
					p.NotifyRenewWeekyActive()
				}
			}
		})
		(<-p.Mdispatr.ChanTimer).Cb()

	}()

	if timeStamp >= int64(p.sqlStruck.StartDailySvrTime)+3600*24 {
		p.NotifyRenewDailyTask()
	}
	if timeStamp >= int64(p.sqlStruck.StartWeekySvrTime)+3600*24*7 {
		p.NotifyRenewWeekyActive()
	}

	GoUtil.RegisterEvent(MergeConst.Notify_Daily_Renew, p.Notify_Daily_Renew, p)

}

func (p *PlayerDailyTaskData) Reconnect(b bool) {

	p.CreateTimer()

}

func (p *PlayerDailyTaskData) ClearData() bool {
	p.SaveDataFromDB("")
	if p.MLeafTimer != nil {
		p.MLeafTimer.Stop()
		p.MLeafTimer = nil
	}
	if p.MTicker != nil {
		p.MTicker.Stop()
		p.MTicker = nil
	}
	GoUtil.RemoveEvent(MergeConst.Notify_Daily_Renew, p.Notify_Daily_Renew, p)
	return true
}
func (p *PlayerDailyTaskData) SaveDataFromDB(Key interface{}) bool {
	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&p.sqlStruck, "t_player_daily_task_data", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&p.sqlStruck, "t_player_daily_task_data")
	}
	p.IsHaveDataDb = true
	return true
}

func (p *PlayerDailyTaskData) ResDailyTaskData(player *Player) {

	p.Data.CurSvrTime = int32(time.Now().Unix())
	agent := p.GetPlayer().GetAgentByPlayer()

	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResDailyTaskData", data)
}

func (p *PlayerDailyTaskData) UpdateDailyTaskData(buf []byte) {
	req := &msg.UpdateDailyTaskData{}

	proto.Unmarshal(buf, req)

	p.Data.NowSortId = req.NowSortId
	p.Data.NowTaskProgress = req.NowTaskProgress
	p.Data.WeekActive = req.WeekActive
	p.Data.TodayTaskList = req.TodayTaskList

	p.sqlStruck.TodayTaskList = strings.Join(req.TodayTaskList, ";")
	p.sqlStruck.NowSortId = req.NowSortId
	p.sqlStruck.NowTaskProgress = req.NowTaskProgress
	p.sqlStruck.WeekyActive = req.WeekActive
	p.SaveDataFromDB("")

}

func (p *PlayerDailyTaskData) NotifyRenewDailyTask() {
	notify := &msg.NotifyRenewDailyTask{}
	notify.DwUin = p.sqlStruck.DwUin
	notify.CurSvrTime = int32(time.Now().Unix())

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyRenewDailyTask", data)
}

func (p *PlayerDailyTaskData) NotifyRenewWeekyActive() {
	notify := &msg.NotifyRenewWeekyActive{}
	notify.DwUin = p.sqlStruck.DwUin
	notify.CurSvrTime = int32(time.Now().Unix())

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyRenewWeekyActive", data)
}

func (p *PlayerDailyTaskData) RenewDailyTaskData(buf []byte) {
	req := &msg.RenewDailyTaskData{}
	proto.Unmarshal(buf, req)

	timeStamp := time.Now().Unix()
	t := time.Unix(timeStamp, 0).Local()
	zero := timeStamp - (int64)(t.Hour()*3600+t.Minute()*60+t.Second())

	p.Data.NowSortId = req.NowSortId
	p.Data.NowTaskProgress = req.NowTaskProgress
	// p.Data.WeekActive = req.WeekActive
	p.Data.TodayTaskList = req.TodayTaskList

	p.sqlStruck.StartDailySvrTime = int32(zero)
	p.sqlStruck.TodayTaskList = strings.Join(req.TodayTaskList, ";")
	p.sqlStruck.NowSortId = req.NowSortId
	p.sqlStruck.NowTaskProgress = req.NowTaskProgress
	// p.sqlStruck.WeekyActive = req.WeekActive

	p.SaveDataFromDB("")
}

func (p *PlayerDailyTaskData) RenewWeekyActiveData(buf []byte) {
	req := &msg.RenewWeekyActiveData{}
	proto.Unmarshal(buf, req)

	p.Data.WeekActive = req.WeekActive

	timeStamp := time.Now().Unix()
	t := time.Unix(timeStamp, 0).Local()

	var week = t.Weekday()
	if t.Weekday() == 0 {
		week = 7
	}

	p.sqlStruck.StartWeekySvrTime = int32(timeStamp - (int64)(week-1)*3600*24 - (int64)(t.Hour()*3600+t.Minute()*60+t.Second()))

	p.sqlStruck.WeekyActive = req.WeekActive
	p.SaveDataFromDB("")
}

/////////////////////////

type PlayerMilestoneData struct {
	*PlayerData
	Data      msg.ResMileStoneData
	sqlStruck db.SqlMileStoneStruct

	// MLeafTimer1 *timer.Timer
}

func (p *PlayerMilestoneData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_milestone_data WHERE dwUin = ?"

	p.Data.MileStoneTaskList = []string{}
	p.sqlStruck = db.SqlMileStoneStruct{}
	p.sqlStruck.DwUin = dwUin.(int32)
	if err := db.SqlDb.Get(&p.sqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}

	p.Data.DwUin = p.sqlStruck.DwUin
	p.Data.Score = p.sqlStruck.MileStoneScore
	p.Data.StartSvrTime = p.sqlStruck.StartMileStoneTime
	p.Data.CurSvrTime = int32(time.Now().Unix())
	p.Data.OpenSvrTime = G_GameLogicPtr.M_SvrGlobal.OpenSvrTime
	if p.sqlStruck.MileStoneTaskList != "" {
		strarr := strings.Split(p.sqlStruck.MileStoneTaskList, ";")

		for i := 0; i < len(strarr); i++ {
			p.Data.MileStoneTaskList = append(p.Data.MileStoneTaskList, strarr[i])
		}
	}

	p.Reconnect(false)
	return true
}

func (p *PlayerMilestoneData) Notify_MileStone_Renew(param []interface{}) {

	p.NotifyRenewMileStone(param[0].(int32))
}

func (p *PlayerMilestoneData) Reconnect(b bool) {
	if p.Data.StartSvrTime < G_GameLogicPtr.M_SvrGlobal.StartMileStoneSvrTime {
		var a1 = []interface{}{G_GameLogicPtr.M_SvrGlobal.StartMileStoneSvrTime}
		p.Notify_MileStone_Renew(a1)
	}
	GoUtil.RegisterEvent(MergeConst.Notify_MileStone_Renew, p.Notify_MileStone_Renew, p)

}

func (p *PlayerMilestoneData) ClearData() bool {
	p.SaveDataFromDB("")

	GoUtil.RemoveEvent(MergeConst.Notify_MileStone_Renew, p.Notify_MileStone_Renew, p)
	return true
}
func (p *PlayerMilestoneData) SaveDataFromDB(Key interface{}) bool {
	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&p.sqlStruck, "t_milestone_data", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&p.sqlStruck, "t_milestone_data")
	}
	p.IsHaveDataDb = true
	return true
}

func (p *PlayerMilestoneData) ResMileStoneData(player *Player) {

	p.Data.CurSvrTime = int32(time.Now().Unix())
	agent := p.GetPlayer().GetAgentByPlayer()

	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResMileStoneData", data)
}

func (p *PlayerMilestoneData) UpdateMileStoneData(buf []byte) {
	req := &msg.UpdateMileStoneData{}

	proto.Unmarshal(buf, req)

	p.Data.MileStoneTaskList = req.MileStoneTaskList
	p.Data.Score = req.Score

	p.sqlStruck.MileStoneTaskList = strings.Join(req.MileStoneTaskList, ";")
	p.sqlStruck.MileStoneScore = req.Score

	p.SaveDataFromDB("")

}

func (p *PlayerMilestoneData) NotifyRenewMileStone(renewTime int32) {
	notify := &msg.NotifyRenewMileStone{}
	notify.DwUin = p.sqlStruck.DwUin
	notify.CurSvrTime = int32(time.Now().Unix())
	notify.StartSvrTime = renewTime

	p.Data.StartSvrTime = renewTime
	p.Data.Score = 0

	p.sqlStruck.StartMileStoneTime = renewTime
	p.sqlStruck.MileStoneScore = 0

	p.SaveDataFromDB("")

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyRenewMileStone", data)
}

func (p *PlayerMilestoneData) RenewMileStoneData(buf []byte) {
	req := &msg.RenewMileStoneData{}
	proto.Unmarshal(buf, req)
	p.Data.Score = req.Score
	p.Data.MileStoneTaskList = req.MileStoneTaskList

	p.sqlStruck.MileStoneTaskList = strings.Join(req.MileStoneTaskList, ";")

	p.SaveDataFromDB("")
}

/////

/////////////////////////

type PlayerPetData struct {
	*PlayerData
	Data      msg.ResPlayerPetData
	sqlStruck db.SqlPlayerPetData

	// MLeafTimer1 *timer.Timer
}

func (p *PlayerPetData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_Pet_Data WHERE dwUin = ?"

	p.sqlStruck = db.SqlPlayerPetData{}
	p.sqlStruck.DwUin = dwUin.(int32)
	if err := db.SqlDb.Get(&p.sqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
		p.sqlStruck.ImageFrame = 1
		p.sqlStruck.ImageIcon = 1
	} else {
		p.IsHaveDataDb = true
	}

	p.Data.DwUin = p.sqlStruck.DwUin
	p.Data.ImageFrame = p.sqlStruck.ImageFrame
	p.Data.ImageIcon = p.sqlStruck.ImageIcon
	p.Data.PetNickName = p.sqlStruck.PetNickName
	p.Data.UnlockFrame = p.sqlStruck.UnlockFrame
	p.Data.UnlockIcon = p.sqlStruck.UnlockIcon

	p.Reconnect(false)
	return true
}

func (p *PlayerPetData) Reconnect(b bool) {

}

func (p *PlayerPetData) ClearData() bool {
	p.SaveDataFromDB("")

	return true
}
func (p *PlayerPetData) SaveDataFromDB(Key interface{}) bool {
	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&p.sqlStruck, "t_player_Pet_Data", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&p.sqlStruck, "t_player_Pet_Data")
	}
	p.IsHaveDataDb = true
	return true
}

func (p *PlayerPetData) ReqPlayerPetData(player *Player) {

	p.SaveDataFromDB("")
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResPlayerPetData", data)
}

func (p *PlayerPetData) ReqUpdatePetProfile(buf []byte) {
	req := &msg.ReqUpdatePetProfile{}
	res := &msg.ResUpdatePetProfile{}
	proto.Unmarshal(buf, req)

	res.Type = req.Type
	res.Param = req.Param
	res.ResultCode = 0
	res.DwUin = p.M_Player.M_DwUin
	if req.Type == 1 {
		p.Data.PetNickName = req.Param
		p.sqlStruck.PetNickName = req.Param
	}
	if req.Type == 2 {
		value, _ := strconv.Atoi(req.Param)
		p.Data.ImageFrame = int32(value)
		p.sqlStruck.ImageFrame = int32(value)
	}
	if req.Type == 3 {
		value, _ := strconv.Atoi(req.Param)
		p.Data.ImageIcon = int32(value)
		p.sqlStruck.ImageIcon = int32(value)
	}

	p.SaveDataFromDB("")
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResUpdatePetProfile", data)
}

/////////////////////////

type Player7DayData struct {
	*PlayerData
	Data      msg.Notify7DayLoginData
	sqlStruck db.SqlNotify7DayLoginData

	// MLeafTimer1 *timer.Timer
}

func (p *Player7DayData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_7DayLogin WHERE dwUin = ?"

	p.sqlStruck = db.SqlNotify7DayLoginData{}
	p.sqlStruck.DwUin = dwUin.(int32)
	if err := db.SqlDb.Get(&p.sqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}
	timeStamp := time.Now().Unix()
	t := time.Unix(timeStamp, 0).Local()
	yuechu := timeStamp - int64(t.Day()-1)*3600*24 - int64(t.Hour())*3600 - int64(t.Minute())*60 - int64(t.Second())
	createRoleTime := int64(p.M_Player.playerdataIF["PlayerBaseData"].(*PlayerBaseData).GetRoleCreateTime())
	if !p.IsHaveDataDb {

		p.sqlStruck.DwUin = dwUin.(int32)
		p.sqlStruck.StartSvrTime = int32(timeStamp) - int32(t.Hour())*3600 - int32(t.Minute())*60 - int32(t.Second())
		p.sqlStruck.GetIndex = 0
		p.sqlStruck.LastGetTime = 0
		p.sqlStruck.MonthScore = int32(t.Day() - 1)
		p.sqlStruck.MonthStartTime = int32(yuechu)

	} else {
		isNew := false
		for {
			if p.sqlStruck.StartSvrTime+7*3600*24 <= int32(timeStamp) {
				p.sqlStruck.StartSvrTime = p.sqlStruck.StartSvrTime + 7*3600*24
				p.sqlStruck.IsCallBack = 0
				isNew = true
			} else {
				break
			}
			if isNew {
				p.sqlStruck.GetIndex = 0
				p.sqlStruck.LastGetTime = 0
			}
		}
		if int32(yuechu) > p.sqlStruck.MonthStartTime {
			p.sqlStruck.MonthScore = 0
			p.sqlStruck.MonthStartTime = int32(yuechu)
		}
	}

	if p.sqlStruck.GetIndex == 0 {
		t1 := time.Unix(createRoleTime, 0).Local()
		DayTime := createRoleTime - int64(t1.Hour())*3600 - int64(t1.Minute())*60 - int64(t1.Second())
		if DayTime+7*24*3600 > timeStamp && DayTime+24*3600 < timeStamp {
			p.sqlStruck.GetIndex = 1
			p.SaveDataFromDB("")
		}
	}

	is7DayCb := p.M_Player.playerdataIF["PlayerBaseData"].(*PlayerBaseData).IsPlayerLoginCallback()
	if is7DayCb {
		p.sqlStruck.StartSvrTime = int32(timeStamp) - int32(t.Hour())*3600 - int32(t.Minute())*60 - int32(t.Second())
		p.sqlStruck.GetIndex = 0
		p.sqlStruck.LastGetTime = 0
		p.sqlStruck.IsCallBack = 1
	}

	p.Data.DwUin = p.sqlStruck.DwUin
	p.Data.StartSvrTime = p.sqlStruck.StartSvrTime
	p.Data.GetIndex = p.sqlStruck.GetIndex
	p.Data.LastGetTime = p.sqlStruck.LastGetTime
	p.Data.MonthScore = p.sqlStruck.MonthScore
	p.Data.MonthStartTime = p.sqlStruck.MonthStartTime
	p.Data.IsCallBack = p.sqlStruck.IsCallBack

	if !p.IsHaveDataDb {
		p.Notify7DayLoginData(int32(time.Now().Unix()))

	}
	p.Reconnect(false)
	return true
}

func (p *Player7DayData) Notify_Daily_Renew(param []interface{}) {

	timeStamp := G_GameLogicPtr.DailyTaskTimestamp
	t := time.Unix(timeStamp, 0).Local()
	yuechu := timeStamp - int64(t.Day()-1)*3600*24 - int64(t.Hour())*3600 - int64(t.Minute())*60 - int64(t.Second())

	for {
		if p.sqlStruck.StartSvrTime+7*3600*24 <= int32(timeStamp) {
			p.sqlStruck.StartSvrTime = p.sqlStruck.StartSvrTime + 7*3600*24
			p.sqlStruck.GetIndex = 0
			p.sqlStruck.LastGetTime = 0
			p.sqlStruck.IsCallBack = 0
		} else {
			break
		}

	}
	if int32(yuechu) > p.sqlStruck.MonthStartTime {
		p.sqlStruck.MonthScore = 0
		p.sqlStruck.MonthStartTime = int32(yuechu)
	}
	createRoleTime := int64(p.M_Player.playerdataIF["PlayerBaseData"].(*PlayerBaseData).GetRoleCreateTime())
	if p.sqlStruck.GetIndex == 0 {
		t1 := time.Unix(createRoleTime, 0).Local()
		DayTime := createRoleTime - int64(t1.Hour())*3600 - int64(t1.Minute())*60 - int64(t1.Second())
		if DayTime+7*24*3600 > timeStamp && DayTime+24*3600 < timeStamp {
			p.sqlStruck.GetIndex = 1
			p.SaveDataFromDB("")
		}
	}

	p.Data.DwUin = p.sqlStruck.DwUin
	p.Data.StartSvrTime = p.sqlStruck.StartSvrTime
	p.Data.GetIndex = p.sqlStruck.GetIndex
	p.Data.LastGetTime = p.sqlStruck.LastGetTime
	p.Data.MonthScore = p.sqlStruck.MonthScore
	p.Data.MonthStartTime = p.sqlStruck.MonthStartTime
	p.Notify7DayLoginData(int32(time.Now().Unix()))
}

func (p *Player7DayData) Reconnect(b bool) {

	GoUtil.RegisterEvent(MergeConst.Notify_Daily_Renew, p.Notify_Daily_Renew, p)
	if b {
		timeStamp := time.Now().Unix()
		t := time.Unix(timeStamp, 0).Local()
		yuechu := timeStamp - int64(t.Day()-1)*3600*24 - int64(t.Hour())*3600 - int64(t.Minute())*60 - int64(t.Second())
		createRoleTime := int64(p.M_Player.playerdataIF["PlayerBaseData"].(*PlayerBaseData).GetRoleCreateTime())
		isNew := false
		for {
			if p.sqlStruck.StartSvrTime+7*3600*24 <= int32(timeStamp) {
				p.sqlStruck.StartSvrTime = p.sqlStruck.StartSvrTime + 7*3600*24
				p.sqlStruck.IsCallBack = 0
				isNew = true
			} else {
				break
			}
			if isNew {
				p.sqlStruck.GetIndex = 0
				p.sqlStruck.LastGetTime = 0
			}
		}
		if int32(yuechu) > p.sqlStruck.MonthStartTime {
			p.sqlStruck.MonthScore = 0
			p.sqlStruck.MonthStartTime = int32(yuechu)
		}

		if p.sqlStruck.GetIndex == 0 {
			t1 := time.Unix(createRoleTime, 0).Local()
			DayTime := createRoleTime - int64(t1.Hour())*3600 - int64(t1.Minute())*60 - int64(t1.Second())
			if DayTime+7*24*3600 > timeStamp && DayTime+24*3600 < timeStamp {
				p.sqlStruck.GetIndex = 1
				p.SaveDataFromDB("")
			}
		}
		p.Data.DwUin = p.sqlStruck.DwUin
		p.Data.StartSvrTime = p.sqlStruck.StartSvrTime
		p.Data.GetIndex = p.sqlStruck.GetIndex
		p.Data.LastGetTime = p.sqlStruck.LastGetTime
		p.Data.MonthScore = p.sqlStruck.MonthScore
		p.Data.MonthStartTime = p.sqlStruck.MonthStartTime
		p.Data.IsCallBack = p.sqlStruck.IsCallBack
		p.Notify7DayLoginData(int32(time.Now().Unix()))
	}
}

func (p *Player7DayData) ClearData() bool {
	p.SaveDataFromDB("")

	GoUtil.RemoveEvent(MergeConst.Notify_Daily_Renew, p.Notify_Daily_Renew, p)
	return true
}
func (p *Player7DayData) SaveDataFromDB(Key interface{}) bool {
	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&p.sqlStruck, "t_player_7DayLogin", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&p.sqlStruck, "t_player_7DayLogin")
	}
	p.IsHaveDataDb = true
	return true
}

func (p *Player7DayData) Res7DaySignal(buf []byte) {
	req := &msg.Req7DaySignal{}
	res := &msg.Res7DaySignal{}
	proto.Unmarshal(buf, req)

	timeStamp := time.Now().Unix()
	t := time.Unix(timeStamp, 0).Local()
	zero := timeStamp - int64(t.Hour())*3600 - int64(t.Minute())*60 - int64(t.Second())

	if int64(p.sqlStruck.LastGetTime) == zero {
		res.ResultCode = MergeConst.Protocol_Active_7Day_Rewarded
	} else {
		res.CurSvrTime = int32(timeStamp)
		res.GetIndex = req.GetIndex
		res.MonthScore = p.sqlStruck.MonthScore + 1
		res.LastGetTime = int32(zero)

		p.sqlStruck.GetIndex = res.GetIndex
		p.sqlStruck.MonthScore = res.MonthScore
		p.sqlStruck.LastGetTime = res.LastGetTime

		p.Data.GetIndex = res.GetIndex
		p.Data.MonthScore = res.MonthScore
		p.Data.LastGetTime = res.LastGetTime
		res.ResultCode = 0
	}
	p.SaveDataFromDB("")
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "Res7DaySignal", data)
}

func (p *Player7DayData) Notify7DayLoginData(renewTime int32) {
	p.Data.CurSvrTime = renewTime
	p.SaveDataFromDB("")
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "Notify7DayLoginData", data)
}

//////////////

type PlayerPetHomeData struct {
	*PlayerData
	Data      msg.ResPetHomeData
	sqlStruck db.SqlPetHomeData
	Mdispatr  *timer.Dispatcher

	MLeafTimer *timer.Timer
}

func (p *PlayerPetHomeData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_PetHome_Data WHERE dwUin = ?"

	p.sqlStruck = db.SqlPetHomeData{}
	p.sqlStruck.DwUin = dwUin.(int32)
	if err := db.SqlDb.Get(&p.sqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}

	if !p.IsHaveDataDb {
		p.sqlStruck.DwUin = dwUin.(int32)
		p.sqlStruck.NestId = 1
		p.sqlStruck.OrnamentsId = 1
	} else {

	}
	timeStamp := time.Now().Unix()
	t := time.Unix(timeStamp, 0).Local()
	t1 := time.Unix(int64(p.sqlStruck.OtherWorkTime), 0).Local()
	if p.sqlStruck.SelfWorkTime+3600*24 < int32(timeStamp) {
		p.sqlStruck.SelfWorkTime = 0

	}

	if timeStamp-int64(t.Hour()*3600)-int64(t.Minute()*60)-int64(t.Second()) != int64(p.sqlStruck.OtherWorkTime)-int64(t1.Hour()*3600)-int64(t1.Minute()*60)-int64(t1.Second()) {
		p.sqlStruck.OtherWorkTime = 0
	}
	isHome := p.GetSelfPetAutoGoHome()
	if isHome {
		p.sqlStruck.AtHome = 0
	}
	p.Data.UnlockDecorateList = []int32{}
	p.Data.SelectDecorateMap = make(map[int32]int32)
	p.SingnalData()

	if p.sqlStruck.SelfWorkTime > 0 {
		go func() {
			// 注释内容也可以使用
			curtime := p.sqlStruck.SelfWorkTime + 3600*24
			t1 := (int64)(curtime) - (int64)(timeStamp)
			p.Mdispatr = timer.NewDispatcher(1)
			p.MLeafTimer = p.Mdispatr.AfterFunc(time.Duration(t1)*time.Second, func() {
				p.sqlStruck.SelfWorkTime = 0

				p.NotifyPetWorkEnd(1)
				p.MLeafTimer = nil
				p.SingnalData()
				p.SaveDataFromDB("")
			})

			(<-p.Mdispatr.ChanTimer).Cb()
		}()
	}
	p.Reconnect(false)

	return true
}

func (p *PlayerPetHomeData) Notify_Daily_Renew(param []interface{}) {

	p.sqlStruck.AtHome = 0
	notify := &msg.NotifyPetGoHome{}
	notify.AtHome = 0
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyPetGoHome", data)

	if p.sqlStruck.OtherWorkTime != 0 {
		p.sqlStruck.OtherWorkTime = 0
		p.SingnalData()
		p.NotifyPetWorkEnd(2)
		p.SaveDataFromDB("")
	}
}

func (p *PlayerPetHomeData) NotifyPetOtherBorrow() {
	if p.sqlStruck.SelfWorkTime == 0 {
		p.sqlStruck.AtHome = 1

		notify := &msg.NotifyPetLeave{}
		notify.AtHome = 1

		agent := p.GetPlayer().GetAgentByPlayer()
		data, _ := proto.Marshal(notify)
		G_getGameLogic().PackResInfo(agent, "NotifyPetLeave", data)
		p.SingnalData()
		p.SaveDataFromDB("")
	}

}

func (p *PlayerPetHomeData) NotifyPetWorkEnd(mtype int32) {
	notify := &msg.NotifyPetWorkEnd{}
	notify.MType = mtype

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyPetWorkEnd", data)
}

func (p *PlayerPetHomeData) Reconnect(b bool) {

	GoUtil.RegisterEvent(MergeConst.Notify_Daily_Renew, p.Notify_Daily_Renew, p)
	if b {
		sqlStr := "SELECT * FROM t_player_PetHome_Data WHERE dwUin = ?"
		db.SqlDb.Get(&p.sqlStruck, sqlStr, p.M_Player.M_DwUin)

		timeStamp := time.Now().Unix()
		t := time.Unix(timeStamp, 0).Local()
		t1 := time.Unix(int64(p.sqlStruck.OtherWorkTime), 0).Local()
		if p.sqlStruck.SelfWorkTime > 0 && p.sqlStruck.SelfWorkTime+3600*24 <= int32(timeStamp) {
			p.sqlStruck.SelfWorkTime = 0
			p.NotifyPetWorkEnd(1)
		}

		if p.sqlStruck.OtherWorkTime > 0 && timeStamp-int64(t.Hour()*3600)-int64(t.Minute()*60)-int64(t.Second()) != int64(p.sqlStruck.OtherWorkTime)-int64(t1.Hour()*3600)-int64(t1.Minute()*60)-int64(t1.Second()) {
			p.sqlStruck.OtherWorkTime = 0
			p.NotifyPetWorkEnd(2)
		}
		isHome := p.GetSelfPetAutoGoHome()
		if isHome {
			p.sqlStruck.AtHome = 0
		}
		p.SingnalData()
		if p.sqlStruck.SelfWorkTime > 0 {
			go func() {
				// 注释内容也可以使用
				curtime := p.sqlStruck.SelfWorkTime + 3600*24
				t1 := (int64)(curtime) - (int64)(timeStamp)
				p.Mdispatr = timer.NewDispatcher(1)
				p.MLeafTimer = p.Mdispatr.AfterFunc(time.Duration(t1)*time.Second, func() {
					p.sqlStruck.SelfWorkTime = 0

					p.NotifyPetWorkEnd(1)
					p.MLeafTimer = nil
					p.SingnalData()
					p.SaveDataFromDB("")
				})

				(<-p.Mdispatr.ChanTimer).Cb()

			}()

		}

		p.SaveDataFromDB("")
	}
}

func (p *PlayerPetHomeData) SingnalData() {

	p.Data.DwUin = p.sqlStruck.DwUin
	p.Data.InterActEndTime = p.sqlStruck.InterActEndTime
	p.Data.NestId = p.sqlStruck.NestId
	p.Data.OrnamentsId = p.sqlStruck.OrnamentsId
	p.Data.CurInterActUin = p.sqlStruck.CurInterActUin
	p.Data.MiniGameResult = p.sqlStruck.MiniGameResult
	p.Data.SelfWorkTime = p.sqlStruck.SelfWorkTime
	p.Data.OtherWorkTime = p.sqlStruck.OtherWorkTime
	p.Data.UnlockPetNest = p.sqlStruck.UnlockPetNest
	p.Data.UnlockPetOrnaments = p.sqlStruck.UnlockPetOrnaments
	p.Data.UnlockPetEmotion = p.sqlStruck.UnlockPetEmotion
	p.Data.AtHome = p.sqlStruck.AtHome
	p.Data.Mood = p.sqlStruck.Mood

	if p.sqlStruck.UnlockDecorateList != "" {
		units := strings.Split(p.sqlStruck.UnlockDecorateList, ";")
		p.Data.UnlockDecorateList = []int32{}
		for i := 0; i < len(units); i++ {
			id, _ := strconv.Atoi(units[i])
			p.Data.UnlockDecorateList = append(p.Data.UnlockDecorateList, int32(id))
		}
	}

	if p.sqlStruck.SelectDecorateMap != "" {
		units := strings.Split(p.sqlStruck.SelectDecorateMap, ";")
		p.Data.SelectDecorateMap = make(map[int32]int32)
		for i := 0; i < len(units); i++ {
			item := strings.Split(units[i], ",")
			type1, _ := strconv.Atoi(item[0])
			id, _ := strconv.Atoi(item[1])
			p.Data.SelectDecorateMap[int32(type1)] = int32(id)
		}
	}
}

func (p *PlayerPetHomeData) ClearData() bool {
	p.SaveDataFromDB("")
	if p.MLeafTimer != nil {
		p.MLeafTimer.Stop()
		p.MLeafTimer = nil
	}
	GoUtil.RemoveEvent(MergeConst.Notify_Daily_Renew, p.Notify_Daily_Renew, p)
	return true
}
func (p *PlayerPetHomeData) SaveDataFromDB(Key interface{}) bool {
	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&p.sqlStruck, "t_player_PetHome_Data", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&p.sqlStruck, "t_player_PetHome_Data")
	}
	p.IsHaveDataDb = true
	return true
}

func (p *PlayerPetHomeData) ReqPetHomeData(player *Player) {
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "ResPetHomeData", data)
}

func (p *PlayerPetHomeData) ReqUnlockDecorate(buf []byte) {
	req := &msg.ReqUnlockDecorate{}
	res := &msg.ResUnlockDecorate{}
	proto.Unmarshal(buf, req)

	isHave := false
	for i := 0; i < len(p.Data.UnlockDecorateList); i++ {
		if p.Data.UnlockDecorateList[i] == req.DecorateId {
			isHave = true
			break
		}
	}
	if !isHave {
		if p.sqlStruck.UnlockDecorateList == "" {
			p.sqlStruck.UnlockDecorateList = strconv.Itoa(int(req.DecorateId))
		} else {
			temp := []string{p.sqlStruck.UnlockDecorateList, strconv.Itoa(int(req.DecorateId))}
			p.sqlStruck.UnlockDecorateList = strings.Join(temp, ",")
		}

	}

	p.SingnalData()
	p.SaveDataFromDB("")
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResUnlockDecorate", data)
}

func (p *PlayerPetHomeData) ReqSaveSelectDecorate(buf []byte) {
	req := &msg.ReqSaveSelectDecorate{}
	res := &msg.ResSaveSelectDecorate{}
	proto.Unmarshal(buf, req)

	for k, v := range req.SelectDecorateMap {
		p.Data.SelectDecorateMap[k] = v
	}
	temp := []string{}
	for k, v := range p.Data.SelectDecorateMap {
		temp = append(temp, strconv.Itoa(int(k))+","+strconv.Itoa(int(v)))
	}
	p.sqlStruck.SelectDecorateMap = strings.Join(temp, ";")
	res.SelectDecorateMap = p.Data.SelectDecorateMap
	// p.SingnalData()
	p.SaveDataFromDB("")
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResSaveSelectDecorate", data)
}

func (p *PlayerPetHomeData) ReqOpenOtherPetHome(buf []byte) {
	req := &msg.ReqOpenOtherPetHome{}
	res := &msg.ResOpenOtherPetHome{}
	proto.Unmarshal(buf, req)

	Profile := G_GameLogicPtr.MPlayerProfileManager.RandomGetAnPlayer(p.Data.DwUin)

	if Profile != nil {
		res.TargetUin = Profile.DwUin

	}
	sqlStr := "SELECT * FROM t_player_PetHome_Data WHERE dwUin = ?"

	sqlStruck := db.SqlPetHomeData{}
	sqlStruck.DwUin = res.TargetUin
	sqlStruck.NestId = 1
	sqlStruck.OrnamentsId = 1
	db.SqlDb.Get(&sqlStruck, sqlStr, res.TargetUin)

	res.NestId = sqlStruck.NestId
	res.OrnamentsId = sqlStruck.OrnamentsId
	res.BriefProfile = &msg.ResPlayerBriefProfileData{}

	if Profile != nil {
		res.BriefProfile.DwUin = res.TargetUin
		res.BriefProfile.ImageFrame = Profile.ImageFrame
		res.BriefProfile.ImageIcon = Profile.ImageIcon
		res.BriefProfile.NickName = Profile.NickName
		res.BriefProfile.PicURL = Profile.PicURL

		DecorateCnt, ActiveTime, _ := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(res.TargetUin)
		res.BriefProfile.DecorateCnt = int32(DecorateCnt)
		res.BriefProfile.ActiveTime = int32(ActiveTime)

	} else {

	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResOpenOtherPetHome", data)
}

func (p *PlayerPetHomeData) ReqShiftVisitPet(buf []byte) {
	req := &msg.ReqShiftVisitPet{}
	res := &msg.ResShiftVisitPet{}
	proto.Unmarshal(buf, req)

	res.TargetUin = req.TargetUin

	sqlStr := "SELECT * FROM t_player_PetHome_Data WHERE dwUin = ?"

	sqlStruck := db.SqlPetHomeData{}
	sqlStruck.DwUin = res.TargetUin
	sqlStruck.NestId = 1
	sqlStruck.OrnamentsId = 1
	db.SqlDb.Get(&sqlStruck, sqlStr, res.TargetUin)

	res.NestId = sqlStruck.NestId
	res.OrnamentsId = sqlStruck.OrnamentsId
	res.BriefProfile = &msg.ResPlayerBriefProfileData{}

	Profile := G_GameLogicPtr.MPlayerProfileManager.GetPlayerProfile(req.TargetUin)
	if Profile != nil {
		res.BriefProfile.DwUin = res.TargetUin
		res.BriefProfile.ImageFrame = Profile.ImageFrame
		res.BriefProfile.ImageIcon = Profile.ImageIcon
		res.BriefProfile.NickName = Profile.NickName
		res.BriefProfile.PicURL = Profile.PicURL

		DecorateCnt, ActiveTime, _ := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(res.TargetUin)
		res.BriefProfile.DecorateCnt = int32(DecorateCnt)
		res.BriefProfile.ActiveTime = int32(ActiveTime)

	} else {
		sql := &db.SqlPlayerProfileStruct{}
		sql.DwUin = req.TargetUin
		sql.ImageFrame = 1
		sql.ImageIcon = 1
		sql.NickName = "Player" + strconv.Itoa(int(req.TargetUin))
		sql.PicURL = ""
		G_GameLogicPtr.MPlayerProfileManager.UpdateNewProfile(sql)

		res.BriefProfile.DwUin = res.TargetUin
		res.BriefProfile.ImageFrame = sql.ImageFrame
		res.BriefProfile.ImageIcon = sql.ImageIcon
		res.BriefProfile.NickName = sql.NickName
		res.BriefProfile.PicURL = sql.PicURL
		DecorateCnt, ActiveTime, _ := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(res.TargetUin)
		res.BriefProfile.DecorateCnt = int32(DecorateCnt)
		res.BriefProfile.ActiveTime = int32(ActiveTime)

	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResShiftVisitPet", data)
}

func (p *PlayerPetHomeData) ReqOpenSelfPet(buf []byte) {
	req := &msg.ReqOpenSelfPet{}
	res := &msg.ResOpenSelfPet{}
	proto.Unmarshal(buf, req)

	res.SelfWorkTime = int32(time.Now().Unix())
	p.sqlStruck.SelfWorkTime = res.SelfWorkTime

	go func() {
		// 注释内容也可以使用
		curtime := p.sqlStruck.SelfWorkTime + 3600*24
		t1 := (int64)(curtime) - (int64)(res.SelfWorkTime)
		p.Mdispatr = timer.NewDispatcher(1)
		p.MLeafTimer = p.Mdispatr.AfterFunc(time.Duration(t1)*time.Second, func() {
			p.sqlStruck.SelfWorkTime = 0

			p.NotifyPetWorkEnd(1)
			p.MLeafTimer = nil
			p.SingnalData()
			p.SaveDataFromDB("")
		})

		(<-p.Mdispatr.ChanTimer).Cb()

	}()
	p.SingnalData()
	p.SaveDataFromDB("")

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResOpenSelfPet", data)
}

func (p *PlayerPetHomeData) ReqCompleteMiniGame(buf []byte) {
	req := &msg.ReqCompleteMiniGame{}
	res := &msg.ResCompleteMiniGame{}
	proto.Unmarshal(buf, req)

	res.DwUin = req.DwUin
	res.TargetUin = req.TargetUin

	sqlStr := "SELECT * FROM t_player_PetHome_Data WHERE dwUin = ?"

	sqlStruck := db.SqlPetHomeData{}
	sqlStruck.DwUin = res.TargetUin
	sqlStruck.NestId = 1
	sqlStruck.OrnamentsId = 1
	db.SqlDb.Get(&sqlStruck, sqlStr, res.TargetUin)

	res.NestId = sqlStruck.NestId
	res.OrnamentsId = sqlStruck.OrnamentsId
	res.InterActEndTime = int32(time.Now().Unix())
	res.Result = req.Result

	p.sqlStruck.OtherWorkTime = res.InterActEndTime
	p.sqlStruck.InterActEndTime = res.InterActEndTime
	p.sqlStruck.MiniGameResult = req.Result

	st := db.SqlPetHomeInterAct{}
	st.DwUin = p.M_Player.M_DwUin
	st.InterActEndTime = res.InterActEndTime
	st.TargetUin = res.TargetUin

	sqlStr1 := "SELECT * FROM t_player_PetHome_InterAct_Data WHERE dwUin = ? And TargetUin = ?"
	ishave := false
	if err := db.SqlDb.Get(&st, sqlStr1, p.Data.DwUin, res.TargetUin); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)

	} else {
		ishave = true
	}

	if req.Result == 3 {
		if ishave {
			db.FormatAllMemUpdateDb(&st, "t_player_PetHome_InterAct_Data", "auto_id")
		} else {
			db.FormatAllMemInsertDb(&st, "t_player_PetHome_InterAct_Data")
		}
		player, ok := G_GameLogicPtr.M_Players[req.TargetUin]
		if ok {
			if player.GetGameData("PlayerPetHomeData") != nil {
				player.GetIFGameData("PlayerPetHomeData").(*PlayerPetHomeData).NotifyPetOtherBorrow()
			} else {
				sqlStr := "SELECT * FROM t_player_PetHome_Data WHERE dwUin = ?"
				sqlStruck := db.SqlPetHomeData{}
				sqlStruck.DwUin = req.TargetUin
				sqlStruck.NestId = 1
				sqlStruck.OrnamentsId = 1

				if err := db.SqlDb.Get(&sqlStruck, sqlStr, req.TargetUin); err != nil {
					sqlStruck.AtHome = 1
					db.FormatAllMemInsertDb(&sqlStruck, "t_player_PetHome_Data")
				} else {
					if sqlStruck.SelfWorkTime+3600*24 <= int32(time.Now().Unix()) {
						sqlStruck.AtHome = 1
					}
					db.FormatAllMemUpdateDb(&sqlStruck, "t_player_PetHome_Data", "dwUin")
				}
			}
		} else {
			sqlStr := "SELECT * FROM t_player_PetHome_Data WHERE dwUin = ?"
			sqlStruck := db.SqlPetHomeData{}
			sqlStruck.DwUin = req.TargetUin
			sqlStruck.NestId = 1
			sqlStruck.OrnamentsId = 1
			if err := db.SqlDb.Get(&sqlStruck, sqlStr, req.TargetUin); err != nil {
				sqlStruck.AtHome = 1
				db.FormatAllMemInsertDb(&sqlStruck, "t_player_PetHome_Data")
			} else {
				if sqlStruck.SelfWorkTime+3600*24 <= int32(time.Now().Unix()) {
					sqlStruck.AtHome = 1
				}
				db.FormatAllMemUpdateDb(&sqlStruck, "t_player_PetHome_Data", "dwUin")
			}

		}

	} else {
		if ishave {
			sqlStr2 := "DELETE FROM " + "t_player_PetHome_InterAct_Data" + " WHERE auto_id = ?"
			db.SqlDb.Exec(sqlStr2, st.AutoId)
		}
		res.InterActEndTime = 0
	}
	if req.IsThief > 0 {
		sqlStr := "SELECT * FROM t_player_card_data WHERE dwUin = ?"
		MsqlStruck := db.SqlCardCollectStruct{}

		err := db.SqlDb.Get(&MsqlStruck, sqlStr, req.TargetUin)
		if err != nil {

		} else {
			if MsqlStruck.CardInfo != "" {
				units := strings.Split(MsqlStruck.CardInfo, ";")
				rate := make(map[int][]int)
				rate[1] = []int{50, 40, 10}
				rate[2] = []int{25, 40, 20, 15}
				if len(units) > 0 {
					CardDetailCfg := gamedata.GetConfigByName("CardDetailCfg")
					cardmap := make(map[int][]*gamedata.CardDetailRecord)

					for i := 0; i < len(units); i++ {
						strr := strings.Split(units[i], ",")
						cnt, _ := strconv.Atoi(strr[1])
						id, _ := strconv.Atoi(strr[0])
						if cnt > 0 {
							cfg := CardDetailCfg.Index(id).(*gamedata.CardDetailRecord)
							value, ok := cardmap[cfg.Color]
							if ok {
								if cfg.IsGold == 0 {
									cardmap[cfg.Color] = append(cardmap[cfg.Color], cfg)
								}

							} else {
								if cfg.IsGold == 0 {
									value = []*gamedata.CardDetailRecord{}
									value = append(value, cfg)
									cardmap[cfg.Color] = value
								}
							}
						}
					}
					weight := 0
					enum := rand.Intn(100) + 1
					index := 0
					for j := 0; j < len(rate[int(req.IsThief)]); j++ {
						weight = rate[int(req.IsThief)][j] + weight
						if weight >= enum {
							index = j
							break
						}
					}
					value, ok := cardmap[index+1]
					if ok {
						temp := rand.Intn(len(value))
						res.CardId = int32(value[temp].Id)
					}
				}
			}

		}
		dataName := G_GameLogicPtr.MLimiteEventManager.GetLimitDataNameById(10)
		p.M_Player.GetIFGameData(dataName).(*PlayerPetRobberData).RemoveTagByPlayerId(req.TargetUin)
	}
	p.SingnalData()
	p.SaveDataFromDB("")

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResCompleteMiniGame", data)
}

func (p *PlayerPetHomeData) GetSelfPetAutoGoHome() bool {
	MPetHomeInterActSTs := []*msg.PetHomeInterActST{}

	sqlStr1 := "SELECT * FROM t_player_PetHome_InterAct_Data WHERE TargetUin = ?"
	st := []db.SqlPetHomeInterAct{}
	if err := db.SqlDb.Select(&st, sqlStr1, p.Data.DwUin); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)

	} else {

	}
	for i := 0; i < len(st); i++ {
		item := &msg.PetHomeInterActST{}
		item.DwUin = st[i].DwUin
		item.TargetUin = st[i].TargetUin
		item.InterActEndTime = st[i].InterActEndTime
		MPetHomeInterActSTs = append(MPetHomeInterActSTs, item)
	}
	sort.Slice(MPetHomeInterActSTs, func(i, j int) bool {
		return MPetHomeInterActSTs[i].InterActEndTime > MPetHomeInterActSTs[j].InterActEndTime
	})
	if len(MPetHomeInterActSTs) > 0 {
		timeStamp := int64(MPetHomeInterActSTs[0].InterActEndTime)
		t := time.Unix(timeStamp, 0).Local()
		zero := timeStamp - (int64)(t.Hour()*3600+t.Minute()*60+t.Second())

		curtime := time.Now().Unix()
		t1 := time.Unix(curtime, 0).Local()
		zero1 := curtime - (int64)(t1.Hour()*3600+t1.Minute()*60+t1.Second())

		if zero1 == zero {
			return false
		}
	}
	return true
}

func (p *PlayerPetHomeData) GetHomeInterActST() []*msg.PetHomeInterActST {
	MPetHomeInterActSTs := []*msg.PetHomeInterActST{}

	sqlStr1 := "SELECT * FROM t_player_PetHome_InterAct_Data WHERE TargetUin = ?"
	st := []db.SqlPetHomeInterAct{}
	db.SqlDb.Select(&st, sqlStr1, p.Data.DwUin)

	for i := 0; i < len(st); i++ {
		item := &msg.PetHomeInterActST{}
		item.DwUin = st[i].DwUin
		item.TargetUin = st[i].TargetUin
		item.InterActEndTime = st[i].InterActEndTime

		dbst := G_GameLogicPtr.MPlayerProfileManager.NewGetPlayerProfile(item.DwUin)

		item.BriefProfile = &msg.ResPlayerBriefProfileData{}
		item.BriefProfile.DwUin = item.DwUin
		item.BriefProfile.ImageFrame = dbst.ImageFrame
		item.BriefProfile.ImageIcon = dbst.ImageIcon
		item.BriefProfile.NickName = dbst.NickName
		item.BriefProfile.PicURL = dbst.PicURL

		DecorateCnt, ActiveTime, _ := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(item.DwUin)
		item.BriefProfile.DecorateCnt = int32(DecorateCnt)
		item.BriefProfile.ActiveTime = int32(ActiveTime)
		MPetHomeInterActSTs = append(MPetHomeInterActSTs, item)
	}
	return MPetHomeInterActSTs
}

func (p *PlayerPetHomeData) ReqPetHomeInterActST(buf []byte) {
	req := &msg.ReqPetHomeInterActST{}
	res := &msg.ResPetHomeInterActST{}
	proto.Unmarshal(buf, req)

	res.MPetHomeInterActSTs = []*msg.PetHomeInterActST{}

	sqlStr1 := "SELECT * FROM t_player_PetHome_InterAct_Data WHERE TargetUin = ?"
	st := []db.SqlPetHomeInterAct{}
	if err := db.SqlDb.Select(&st, sqlStr1, p.Data.DwUin); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)

	} else {

	}
	for i := 0; i < len(st); i++ {
		item := &msg.PetHomeInterActST{}
		item.DwUin = st[i].DwUin
		item.TargetUin = st[i].TargetUin
		item.InterActEndTime = st[i].InterActEndTime

		dbst := G_GameLogicPtr.MPlayerProfileManager.NewGetPlayerProfile(item.DwUin)

		item.BriefProfile = &msg.ResPlayerBriefProfileData{}
		item.BriefProfile.DwUin = item.DwUin
		item.BriefProfile.ImageFrame = dbst.ImageFrame
		item.BriefProfile.ImageIcon = dbst.ImageIcon
		item.BriefProfile.NickName = dbst.NickName
		item.BriefProfile.PicURL = dbst.PicURL

		DecorateCnt, ActiveTime, _ := G_GameLogicPtr.MPlayerProfileManager.GetPlayerDecorate(item.DwUin)
		item.BriefProfile.DecorateCnt = int32(DecorateCnt)
		item.BriefProfile.ActiveTime = int32(ActiveTime)
		res.MPetHomeInterActSTs = append(res.MPetHomeInterActSTs, item)
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResPetHomeInterActST", data)
}

func (p *PlayerPetHomeData) ReqCallBackPet(buf []byte) {
	req := &msg.ReqCallBackPet{}
	res := &msg.ResCallBackPet{}
	proto.Unmarshal(buf, req)
	p.sqlStruck.AtHome = 0
	p.SingnalData()
	p.SaveDataFromDB("")

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResCallBackPet", data)
}

///////////////

type Player7DayCallBackData struct {
	*PlayerData
	Data      msg.Notify7DayCallbackData
	sqlStruck db.SqlNotify7DayCallbackData

	// MLeafTimer1 *timer.Timer
}

func (p *Player7DayCallBackData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_callback_7Day WHERE dwUin = ?"

	p.sqlStruck = db.SqlNotify7DayCallbackData{}
	p.sqlStruck.DwUin = dwUin.(int32)
	if err := db.SqlDb.Get(&p.sqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}

	p.Data.DwUin = p.sqlStruck.DwUin
	p.Data.StartSvrTime = p.sqlStruck.StartSvrTime
	p.Data.GetIndex = p.sqlStruck.GetIndex
	p.Data.LastGetTime = p.sqlStruck.LastGetTime

	return true
}
func (p *Player7DayCallBackData) OpenNewCallBack() {
	timeStamp := time.Now().Unix()
	t := time.Unix(timeStamp, 0).Local()

	p.sqlStruck.StartSvrTime = int32(timeStamp) - int32(t.Hour())*3600 - int32(t.Minute())*60 - int32(t.Second())
	p.sqlStruck.GetIndex = 0
	p.sqlStruck.LastGetTime = 0

	p.Data.DwUin = p.sqlStruck.DwUin
	p.Data.StartSvrTime = p.sqlStruck.StartSvrTime
	p.Data.GetIndex = p.sqlStruck.GetIndex
	p.Data.LastGetTime = p.sqlStruck.LastGetTime
	p.SaveDataFromDB("")

	p.Notify7DayCallbackData(int32(time.Now().Unix()))
	p.Reconnect(false)
}

func (p *Player7DayCallBackData) ProcessIsOutline() {
	timeStamp := time.Now().Unix()

	if p.sqlStruck.StartSvrTime+7*3600 <= int32(timeStamp) {

	} else {

		p.Notify7DayCallbackData(int32(timeStamp))
	}
}

func (p *Player7DayCallBackData) Notify_Daily_Renew(param []interface{}) {

	timeStamp := G_GameLogicPtr.DailyTaskTimestamp

	if p.sqlStruck.StartSvrTime+7*3600*24 <= int32(timeStamp) {
		p.Notify7DayCallbackEnd()
	} else {
		p.Data.DwUin = p.sqlStruck.DwUin
		p.Data.StartSvrTime = p.sqlStruck.StartSvrTime
		p.Data.GetIndex = p.sqlStruck.GetIndex
		p.Data.LastGetTime = p.sqlStruck.LastGetTime
		p.Notify7DayCallbackData(int32(timeStamp))
	}
}

func (p *Player7DayCallBackData) Reconnect(b bool) {

	GoUtil.RegisterEvent(MergeConst.Notify_Daily_Renew, p.Notify_Daily_Renew, p)

}

func (p *Player7DayCallBackData) ClearData() bool {
	p.SaveDataFromDB("")

	GoUtil.RemoveEvent(MergeConst.Notify_Daily_Renew, p.Notify_Daily_Renew, p)
	return true
}
func (p *Player7DayCallBackData) SaveDataFromDB(Key interface{}) bool {
	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&p.sqlStruck, "t_player_callback_7Day", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&p.sqlStruck, "t_player_callback_7Day")
	}
	p.IsHaveDataDb = true
	return true
}

func (p *Player7DayCallBackData) Req7DayCallbackSignal(buf []byte) {
	req := &msg.Req7DayCallbackSignal{}
	res := &msg.Res7DayCallbackSignal{}
	proto.Unmarshal(buf, req)

	timeStamp := time.Now().Unix()
	t := time.Unix(timeStamp, 0).Local()
	zero := timeStamp - int64(t.Hour())*3600 - int64(t.Minute())*60 - int64(t.Second())

	if int64(p.sqlStruck.LastGetTime) == zero {
		res.ResultCode = MergeConst.Protocol_Active_7Day_Rewarded
	} else {
		res.CurSvrTime = int32(timeStamp)
		res.GetIndex = req.GetIndex
		res.LastGetTime = int32(zero)
		p.sqlStruck.GetIndex = res.GetIndex
		p.sqlStruck.LastGetTime = res.LastGetTime
		p.Data.GetIndex = res.GetIndex
		p.Data.LastGetTime = res.LastGetTime
		res.ResultCode = 0
	}
	p.SaveDataFromDB("")
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "Res7DayCallbackSignal", data)
}

func (p *Player7DayCallBackData) Notify7DayCallbackData(renewTime int32) {
	p.Data.CurSvrTime = renewTime
	p.SaveDataFromDB("")
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.Data)
	G_getGameLogic().PackResInfo(agent, "Notify7DayCallbackData", data)
}

func (p *Player7DayCallBackData) Notify7DayCallbackEnd() {

	notify := msg.Notify7DayCallbackEnd{}
	notify.DwUin = p.M_Player.M_DwUin

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&notify)
	G_getGameLogic().PackResInfo(agent, "Notify7DayCallbackEnd", data)
}

// ////////////
type PlayerNewInfinitePackData struct {
	*PlayerData

	MsqlStruck db.SqlLimitInfinitePackStruct
}

func (p *PlayerNewInfinitePackData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_new_LimitInfinitePack WHERE dwUin = ?"
	p.MsqlStruck = db.SqlLimitInfinitePackStruct{}

	if err := db.SqlDb.Get(&p.MsqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}
	p.MsqlStruck.DwUin = dwUin.(int32)
	timeStamp := time.Now().Unix()
	t := time.Unix(timeStamp, 0).Local()
	zero := timeStamp - int64(t.Hour())*3600 - int64(t.Minute())*60 - int64(t.Second())

	if p.MsqlStruck.StartSvrTime < int32(zero) {
		p.MsqlStruck.StartSvrTime = int32(zero)
		p.MsqlStruck.EndSvrTime = int32(zero) + 3600*24
		p.MsqlStruck.CurGear = 0

	}

	p.Reconnect(false)
	return true
}

func (p *PlayerNewInfinitePackData) Notify_Daily_Renew(args []interface{}) {
	timeStamp := G_GameLogicPtr.DailyTaskTimestamp
	t := time.Unix(timeStamp, 0).Local()
	zero := timeStamp - int64(t.Hour())*3600 - int64(t.Minute())*60 - int64(t.Second())

	p.MsqlStruck.StartSvrTime = int32(zero)
	p.MsqlStruck.EndSvrTime = int32(zero) + 3600*24
	p.MsqlStruck.CurGear = 0
	p.SaveDataFromDB("")
	p.NotifyRefreshInfinitePack()

}

func (p *PlayerNewInfinitePackData) NotifyRefreshInfinitePack() {

	res := &msg.NotifyRefreshInfinitePack{}
	res.ActiveID = p.MsqlStruck.ActiveID
	res.CurSvrTime = int32(time.Now().Unix())
	res.StartSvrTime = p.MsqlStruck.StartSvrTime
	res.EndSvrTime = p.MsqlStruck.EndSvrTime
	res.CurGear = p.MsqlStruck.CurGear
	res.DwUin = p.M_Player.M_DwUin
	res.ResultCode = 0

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "NotifyRefreshInfinitePack", data)
}

func (p *PlayerNewInfinitePackData) Reconnect(b bool) {
	GoUtil.RemoveEvent(MergeConst.Notify_Daily_Renew, p.Notify_Daily_Renew, p)
	GoUtil.RegisterEvent(MergeConst.Notify_Daily_Renew, p.Notify_Daily_Renew, p)
	if b {
		timeStamp := time.Now().Unix()
		t := time.Unix(timeStamp, 0).Local()
		zero := timeStamp - int64(t.Hour())*3600 - int64(t.Minute())*60 - int64(t.Second())

		if p.MsqlStruck.StartSvrTime < int32(zero) {
			p.MsqlStruck.StartSvrTime = int32(zero)
			p.MsqlStruck.EndSvrTime = int32(zero) + 3600*24
			p.MsqlStruck.CurGear = 0
			p.SaveDataFromDB("")
			p.NotifyRefreshInfinitePack()
		}
	}
}

func (p *PlayerNewInfinitePackData) ResInfinitePackDetail(buf []byte) {
	req := &msg.ReqInfinitePackDetail{}
	proto.Unmarshal(buf, req)
	st := p.MsqlStruck
	res := &msg.ResInfinitePackDetail{}

	res.ActiveID = st.ActiveID
	res.CurSvrTime = int32(time.Now().Unix())
	res.StartSvrTime = st.StartSvrTime
	res.EndSvrTime = st.EndSvrTime
	res.CurGear = st.CurGear
	res.DwUin = p.M_Player.M_DwUin
	res.ResultCode = 0

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResInfinitePackDetail", data)
}

func (p *PlayerNewInfinitePackData) ResBuyInfinitePack(buf []byte) {
	req := &msg.ReqBuyInfinitePack{}
	proto.Unmarshal(buf, req)

	res := &msg.ResBuyInfinitePack{}

	res.ActiveID = p.MsqlStruck.ActiveID
	res.DwUin = p.M_Player.M_DwUin
	res.ResultCode = 0
	res.CurGear = req.CurGear + 1
	p.MsqlStruck.CurGear = req.CurGear + 1

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResBuyInfinitePack", data)
}

func (p *PlayerNewInfinitePackData) SaveDataFromDB(Key interface{}) bool {
	if p.IsHaveDataDb {
		db.FormatAllMemUpdateDb(&p.MsqlStruck, "t_player_new_LimitInfinitePack", "dwUin")
	} else {
		db.FormatAllMemInsertDb(&p.MsqlStruck, "t_player_new_LimitInfinitePack")
	}

	p.IsHaveDataDb = true
	return true
}
func (p *PlayerNewInfinitePackData) ClearData() bool {
	p.SaveDataFromDB("")
	GoUtil.RemoveEvent(MergeConst.Notify_Daily_Renew, p.Notify_Daily_Renew, p)

	return true
}
